【问题标题】:Rails relation overloadRails 关系重载
【发布时间】:2011-05-07 12:01:13
【问题描述】:

假设我有以下模型:

Class Wishlist
    belongs_to :user # User class is irrelevant here
    has_many :inclusions
    has_many :products, :through => :inclusions
  end

  Class Product
    has_many :inclusions
    has_many :wishlists, :through => :inclusions
  end

  Class Inclusion
    belongs_to :product
    belongs_to :wishlist
  end

inclusions/index.html.erb

  <%= render @inclusions %>

inclusions/_inclusion.html.erb

  <%= "#{ inclusion.quantity } #{ inclusion.product.name } #{ inclusion.wishlist.user.name }"%>

这个例子是微不足道的,但重点是:数据库查询的数量是压倒性的。对于 _inclusion.html.erb 的每个实例,似乎至少创建了三个新查询。 有没有办法预先获取这些信息,可能是通过 JOIN 命令?

【问题讨论】:

    标签: sql ruby-on-rails ruby join model


    【解决方案1】:

    也许这会有所帮助:

     @inclusions = Inclusions.includes(:product, { :wishlist => :user })
    

    阅读有关预加载的信息。

    【讨论】:

      【解决方案2】:

      您是否考虑过创建 sql 视图,例如 ProductsWishlist 并(如果性能不好)实现它?

      http://ss64.com/ora/syntax-views.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-30
        • 2012-11-11
        • 2015-12-16
        • 2018-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多