Inner Join help


#1

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


#2

On Jun 8, 5:18 am, Scott H. removed_email_address@domain.invalid
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


#3

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’