JosephA91 JosephA91 - 1 year ago 56
Ruby Question

How to target a model and access records nested two levels deep in Ruby on Rails?

I am trying to create a todo list application in ruby on rails that has 3 models as nested resources.

For Example:

  • User:
    has_many :todo_lists

  • TodoList:
    has_many :todo_items
    belongs_to :user

  • TodoItem:
    belongs_to :todo_list
    scope :completed, -> { where.not(completed_at: nil) }

returns the user's todo lists.

returns the todo list's todo items.

returns the todo list's completed todo items.


returns error:
NoMethodError: undefined method 'todo_items'

also returns error:
NoMethodError: undefined method 'todo_items'

We have tried
which returns all the todo items for a user but we cannot add the

Am I on the right track?

Answer Source

Try using has_many :through association.

In your user model define association:

has_many :todo_items, through: :todo_lists

You should than be able to get todo_items without getting todo_lists first.


Using the map you were on the right track. { |todo_list| todo_list.todo_items.completed }.flatten
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download