【发布时间】:2018-10-21 18:17:10
【问题描述】:
我的场景如下
公司 has_many 购买作为多态关系
用户 has_many 购买是一种多态关系
注意:用户和公司之间没有关系
购买属于_to多态性
购买has_many 物品
用户通过购买拥有_many 个项目
代码方面
class User
has_many :purchases, as: :purchasable, dependent: :destroy
has_many :items, through: :purchases
end
class Purchase
belongs_to :purchasable, polymorphic: true
has_many :items, dependent: :destroy
end
class Item
belongs_to :purchase
end
问题 1:
User.first.items 的适当索引是什么?
问题 2: 我想查找最近购买的物品,按物品类别对其进行分组。最有效的索引/arel/sql 是什么?当前,我确信效率低下,代码如下
class User
def most_recent_items
item_ids = Item.select("MAX(id) AS id").group(:category, :puchase_id).collect(&:id) & items.collect(&:id)
Item.order("created_at DESC").where(:id => item_ids)
end
end
【问题讨论】:
标签: mysql ruby-on-rails-4 activerecord indexing arel