belongs_to :through

796 views
Skip to first unread message

TomRossi7

unread,
Nov 5, 2010, 1:13:06 PM11/5/10
to Ruby on Rails: Talk
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

Erol Fornoles

unread,
Nov 5, 2010, 1:39:26 PM11/5/10
to rubyonra...@googlegroups.com
What you're really looking for is has_one :through.

--
Erol M. Fornoles

TomRossi7

unread,
Nov 5, 2010, 1:49:27 PM11/5/10
to Ruby on Rails: Talk
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

Tim Shaffer

unread,
Nov 5, 2010, 2:18:37 PM11/5/10
to Ruby on Rails: Talk
On Nov 5, 1:13 pm, TomRossi7 <t...@themolehill.com> wrote:
> 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

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"

TomRossi7

unread,
Nov 5, 2010, 2:31:17 PM11/5/10
to Ruby on Rails: Talk
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.
Reply all
Reply to author
Forward
0 new messages