I’m new to rails and like many I seem to be having challenges figuring out how ActiveRecord and associations work.
I have three models, user, projects and tasks:
Class User < ActiveRecord::Base
has_many :projects
has_many :tasks
end
Class Project < ActiveRecord::Base
has_many :tasks
belongs_to :user
end
Class Task < ActiveRecord::Base
belongs_to :projects
belongs_to :user
end
Both Projects and Tasks both have the field user_id. Tasks has the field project_id.
I expect to be able to look up all the Projects and Tasks through the user. However, every time I try, I get a blank array even though there are Projects and Tasks:
usr = User.find(1)
=> [User id: 1, name: "Some Guy"]
usr.projects
=> []
usr.tasks
=> []
It does work when I query for Tasks through Projects:
proj = Project.find(1)
=> [#<Project id: 1, user_id: 1, description: "Some Project">]
proj.tasks
=> [#<Task id: 1, user_id: 1, project_id: 1, description: "Do Something">,
#<Task id: 2, user_id: 1, project_id: 1, description: "Do another thing">]
I believe that the has_many and belongs_to settings are correct since I have other models connected to the User and they work correctly. Any ideas what I’m missing?
I figured it out by changing the model associations. I removed the
belongs_to :userfrom the Task model and added ahas_many :throughrelationship to the User model:After restarting the console, I can now pull up tasks that belong to the user in the way I was originally trying: