Double join with habtm in ActiveRecord

Posted by Daniel Huckstep on Stack Overflow See other posts from Stack Overflow or by Daniel Huckstep
Published on 2009-07-29T23:15:54Z Indexed on 2010/04/22 5:13 UTC
Read the original article Hit count: 175

I have a weird situation involving the need of a double inner join. I have tried the query I need, I just don't know how to make rails do it.

The Data

  • Account (has_many :sites)
  • Site (habtm :users, belongs_to :account)
  • User (habtm :sites)

Ignore that they are habtm or whatever, I can make them habtm or has_many :through.

I want to be able to do

@user.accounts

or

@account.users

Then of course I should be able to do

@user.accounts < @some_other_account

And then have @user.sites include all the sites from @some_other_account.

I've fiddled with habtm and has_many :through but can't get it to do what I want.

Basically I need to end up with a query like this (copied from phpmyadmin. Tested and works):

SELECT accounts.* 
FROM accounts
INNER JOIN sites ON sites.account_id = accounts.id
INNER JOIN user_sites ON sites.id = user_sites.site_id
WHERE user_sites.user_id = 2

Can I do this? Is it even a good idea to have this double join? I am assuming it would work better if users had the association with accounts to begin with, and then worry about getting @user.sites instead, but it works better for many other things if it is kept the way it is (users <-> sites).

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord