has_many通过has_and_belongs_to_many关联

时间:2013-12-09 23:16:22

标签: ruby-on-rails ruby-on-rails-4

我有以下课程:

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

我的联系表:

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

我想在公司设立一个协会,返回与公司人员相关的所有交易的明确列表。有什么想法吗?

我尝试按照建议进行以下更改:

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

但是这会生成以下在ORDER BY子句上失败的SQL。交易没有名字/姓氏字段,但人们确实如此。

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]]

1 个答案:

答案 0 :(得分:0)

company.rb

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

company.trades应该为您提供属于公司员工的所有交易。