megas
megas

Reputation: 21791

List through has_many

I have this db schema

class User
  has_many :accounts
end

class Account
  belongs_to :user
  belongs_to :biller
end

class Biller
  has_many :accounts
end

How to get a list of billers of the user?

billers = user.?

Upvotes: 0

Views: 580

Answers (1)

bronislav
bronislav

Reputation: 782

Add has_many association with thorough option:

class User
  has_many :accounts
  has_many :billers, through: :accounts 
end

class Account
  belongs_to :user
  belongs_to :biller
end

class Biller
  has_many :accounts
end

And use it like follow:

billers = user.billers

More information see in the Active Record guide.

Upvotes: 2

Related Questions