belongs_to :through

Why is belongs_to :through not an option with Rails? I'm sure there is something I'm missing! I find myself wanting it more now with lazy loading in Rails 3.

project belongs_to client

task belongs_to project task belongs_to client :through project

I can work around it by just creating a method on the task model called client and just returns project.client, but that isn't as beautiful!

Thanks, Tom

What you’re really looking for is has_one :through.

I'm not sure how the has_one relationship is translating for scopes, but here is an example that causes problems:

Task.joins(:client).where('clients.name' => 'test')

results in the following SQL:

SELECT `tasks`.* FROM `tasks` INNER JOIN `projects` ON `tasks`.`id` IS NULL INNER JOIN `clients` ON `clients`.`id` = `projects`.`client_id` WHERE (`clients`.`name` = 'test')

I realize I can do Task.joins(:project => :client), but that is what I am trying to avoid for my complicated scopes.

Thanks, Tom

belongs_to :through is not necessary, which is why it's not an option.

So you are saying your tables would look like this:

TASK name project_id

PROJECT name client_id

CLIENT name

And you would like to be able to find all tasks for a given client?

In that case, you would say client has_many :tasks, :through => :project

Then instead of "Task.joins(:project => :client)" You can do "Client.find_by_name('asdf').tasks"

belongs_to :through definitely is not necessary just like has_many :through is not necessary and wasn't even included in earlier releases of Rails. With Rails 3, creating scopes that are lazily loaded provides a lot of functionality that would be nice to extend to the belongs_to :through relationship.