我有以下类别:的has_many通过has_and_belongs_to_many协会
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
但是,生成以下SQL从而未能在ORDER BY子句。交易没有名字/姓氏字段,但人们会这样做。
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]]
在您的查询中,您可以更改.distinct http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields –
我开始怀疑我是否发现了错误。如果我在Person和Trade上有默认的作用域,我会搞砸ORDER BY子句。如果我删除范围,事情工作。 –
有时ORM失败,因此您可以尝试自己放置查询。使用ActiveRecord :: Base.connection.execute(“SQL查询”) –