我有一個Transaction
模型,它與Product
和Service
都有多態關聯。Rails 4 - 多態關聯之間的複雜查詢
這是遷移:
create_table :products do |t|
t.string :name
t.timestamps null: false
end
create_table :services do |t|
t.string :name
t.integer :duration
t.timestamps null: false
end
create_table :transactions do |t|
t.integer :amount
t.decimal :price
t.references :sellable, polymorphic: true, index: true
t.references :bill, index: true, foreign_key: true
t.timestamps null: false
end
這是該機型
class Transaction < ActiveRecord::Base
belongs_to :bill
belongs_to :sellable, polymorphic: true
def total; price * amount; end
end
class Product < ActiveRecord::Base
has_many :transactions, as: :sellable
end
class Service < ActiveRecord::Base
has_many :transactions, as: :sellable
end
基本上每一筆交易都知道哪些項目被出售,每個單位多少個單位,多少成本覈算。
如何通過出售的單位獲得前5個對象?
如何獲得前5名的對象,單位是否帶入金錢?
它不是關於計數行。一筆交易可能賣出多於一個單位 –
那麼您是否也不應該在交易表中指明一列?對不起,如果我沒有得到你的數據庫結構。你能解釋一下你如何計算單位嗎? –
交易中的字段「amount」正好表示... –