Let's say I have three models.
User
, Tool
and Work
(actually the models are different but for simplicity sake it's these guys). Now..
I User
is given Tool
and Tool
does some Work
.
User has many Tools
every Tool belongs to one User
Tool has many Works
every Work was done with single Tool
I can successfully get User.tools
but I can't get the Works done by user.
I tried:
User.tools.each do |tool|
tool.works.each do |work|
<%= work.id %>
end
end
but that did not exactly go as expected (multiple id's of Works a User has done), instead I got error...
What do I do wrong?
You can create a many-to-many association for the same :
class User < ActiveRecord::Base
has_many :tools
has_many :tasks , :through => :tools, :source => :works
end
class Tool < ActiveRecord::Base
belongs_to :user
has_many :works
end
class Work < ActiveRecord::Base
belongs_to :tool
end
Now you can do :
@users = User.all
@users.each do |user|
user.tasks do |task|
<%= task.id %>
end
end
Make sure, the migration is correct. All the foreign_key/primary key relationship should be correct, otherwise you will get undefined column error. Check the #has_many
official doc to understand the options I passed with the has_many
method call.