Forum: Ruby on Rails Inner Join help

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
60071e44382435f0f42bf6c3f6e29889?d=identicon&s=25 Scott Holland (ginsberg1982)
on 2009-06-08 06:18
Hello!

I want to limit my model to just show companies from the current users
account:

user.account.companies

I have this in my model which seems to be working:

def self.find(*args)
    args << {:conditions => XXXXX"}
    super
end


Now I just need to turn this sql into rails conditions:


SELECT `companies`.* FROM `companies` INNER JOIN `users` ON
`companies`.user_id = `users`.id WHERE ((`users`.account_id = 1))

Can anyone help with this?

Thanks

Scott
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-06-08 10:23
(Received via mailing list)
On Jun 8, 5:18 am, Scott Holland <rails-mailing-l...@andreas-s.net>
wrote:
>     args << {:conditions => XXXXX"}
>     super
> end
>
I would question the wisdom of doing that - it may work in the short
term, but you may find it breaks other stuff.

> Now I just need to turn this sql into rails conditions:
>
> SELECT `companies`.* FROM `companies` INNER JOIN `users` ON
> `companies`.user_id = `users`.id WHERE ((`users`.account_id = 1))
>

Take a look at the :joins option to find (if you have the associations
right you don't even need to write out the join clause in full,
specifying the name of the association is enough).

In this case though I'm not sure why you wouldn't just do
some_user.account.companies; you'd get back the same result set.


Fred
60071e44382435f0f42bf6c3f6e29889?d=identicon&s=25 Scott Holland (ginsberg1982)
on 2009-06-10 19:31
> I would question the wisdom of doing that - it may work in the short
> term, but you may find it breaks other stuff.

Thanks for the reply - I've just discovered default_scope, which is
exactly what I want. Now I just have to figure out how to do the inner
join in rails.


> In this case though I'm not sure why you wouldn't just do
> some_user.account.companies; you'd get back the same result set.

I have that association set up and it works fine. However, all the data
in my app is associated to the current user/account. I want to set up
the scope in one place and not have to worry about it every time i do a
'find'
This topic is locked and can not be replied to.