【发布时间】:2016-01-05 11:38:13
【问题描述】:
我有一个Transaction 模型,它与Product 和Service 都具有多态关联。
这是迁移:
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 名的物品,按收入单位计算?
【问题讨论】:
标签: ruby-on-rails associations polymorphic-associations