【问题标题】:Rails 4: model relationships and indexing for two has_many through modelsRails 4:两个 has_many 通过模型的模型关系和索引
【发布时间】: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


    【解决方案1】:

    至于您的第一个问题,我不确定我是否理解您所说的“适当的索引”是什么意思 - 但如果您的意思是调用 user.items 对您不起作用,我认为最简单的解决方案是创建User.rb 中的类方法。

    def items
      purchases.map(&:items).flatten
    end
    

    至于第二种,您可以通过多种方式订购商品。如果您的结果是 ActiveRecord 集合,那么您可以使用order,就像您在示例中一样。如果结果是一个数组,我建议使用sort_by 方法。

    def most_recent_items
      self.items.sort_by(&:created_at)
    end
    

    请注意,如果这种排序方式无法将您的项目按您想要的顺序排列,您可以在末尾添加 .reverse。希望这会有所帮助!

    【讨论】:

    • 我遇到的问题是 db 表非常大,有 2 多万条记录,而且两个查询都很慢。所以 user.items 可以工作,但是速度很慢,我想看看应该向数据库添加哪些索引以加快速度。
    • 啊,如果您关心速度,我建议您使用 elasticsearch / searchkick gem。它将索引模型的所有字段并比 ActiveRecord 查询更快地解析该数据。害羞,您必须减少存储在项目上的数据,可能会使用更多关联并在 Item 对象上存储更少。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    相关资源
    最近更新 更多