简体   繁体   中英

has_many through a has_and_belongs_to_many association

I have the following classes:

company.rb

class Company < ActiveRecord::Base
  has_many :people
end

person.rb

class Person < ActiveRecord::Base
  belongs_to :company
  has_and_belongs_to_many :trades
end

trade.rb

class Trade < ActiveRecord::Base
  has_and_belongs_to_many :people
end

And my join table:

create_table "people_trades", id: false, force: true do |t|
  t.integer "trade_id"
  t.integer "person_id"
end

I would like to place an association on Company that returns a distinct list of all Trades related to the Company's People. Any ideas?

I tried making the following change as suggested:

class Company < ActiveRecord::Base
  has_many :people
  has_many :trades, through: :people, :uniq => true
end

But that generates the following SQL which fails on the ORDER BY clause. Trades do not have first/last name fields, people does though.

SELECT DISTINCT "trades".* FROM "tratrades"."id" = "people_trades"."trade_id" 
INNER JOIN "people" ON "people_trades"."person_id" = "people"."id" 
WHERE "people"."company_id" = ? 
ORDER BY "trades"."name" ASC, "trades"."last_name" ASC, "trades"."first_name" ASC  [["company_id", 1]]

company.rb

class Company < ActiveRecord::Base
  has_many :people
  has_many :trades, through: :people
end

company.trades should then give you all the trades that belong to people in the company.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM