If you have the following models:
client has_many :projects
project has_many :tasks
tasks has_many :timeentries
and
timeentries belongs_to :task
task belongs_to :project
project belongs_to :client
Then do you need model statements like:
timeentries belongs_to project :through => :tasks
client has_many :tasks, :through => :projects
Thanks
The simple answer is that you don’t have to, but you might want to. It depends a bit how you are going to use your model- if you want to be able to access each end of the relationship from the other then you might need it. So if you wanted to be able to access Project directly from
TimeEntries.Projectthen you might want it, if you are happy to go throughTimeEntries.Task.Projectthen you don’t need the explicit relationship, which can complicate matters further on.Be aware of Has_and_belongs_to_many :through which is for cases where you have a many-to-many relationship using an intermediary table purely to represent the relationship so the intermediary doesn’t need it’s own model.
This is quite common in two-way many-to-many relationships- supposing you have a tag cloud of some kind you might have something like this:
There one article can have many tags, one tag can be applied to many articles, so you don’t want to bind either in the table. So the Article has_many Tags through ArticleTag.
This gives a handy summary of associations in Rails.