Home > database >  How to get object from has_many of has_many relations in Rails
How to get object from has_many of has_many relations in Rails

Time:12-08

I got models to call Task and User

In Task Model I reference the task its-self like below

belongs_to :parent, optional: true, class_name: "Task"
has_many :children, class_name: "Task",foreign_key: "parent_id"

In the User model, one user can have many assigned tasks.

has_many :tasks, foreign_key: "assignee"

So in case, I want to render a children tasks of tasks which are assigned for a user. What should I do? I use

@children_tasks = @user.tasks.children

But it does not work as I expected. Any ideas?

CodePudding user response:

You need to search for tasks that has parent equal to the users tasks.

Try : Task.where(parent: @user.tasks)

  • Related