Dual connection with habtm in ActiveRecord

I have a strange situation related to the need for a double internal connection. I tried the query that I need, I just don't know how to make rails.

Data

  • Account (has_many: sites)
  • Website (habtm: users, owned_to: account)
  • User (habtm: sites)

Ignore that they are habtm or something else, 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 would have to do

@user.accounts < @some_other_account

And then @ user.sites includes all the sites from @some_other_account.

I searched habtm and has_many: through, but can't get it to do what I want.

Basically, I need to make such a request (copied from phpmyadmin. Tested and working):

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

? , ? , , , , @user.sites , , , (users < > ).

+3
2

, , . .

# in user.rb
def accounts
  Account.all(:include => {:sites => :users}, :conditions => ["users.id=?", self])
end

def add_account(other_account)
  other_account.sites.each do |site|
    self.sites << site
  end
end

# in account.rb
def users
  User.all(:include => {:sites => :account}, :conditions => ["accounts.id=?", self])
end

, HABTM, has_many :through. , , .

- has_many :through, .

+3

Source: https://habr.com/ru/post/1713910/


All Articles