我有以下類別:的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查詢」) –