Rails 4 - 设置包含模型的限制

时间:2014-03-07 08:14:54

标签: ruby-on-rails

我有像这样的多对多关联(为方便起见,它已被简化)

class Product
  has_many :categorizations
  has_many :categories, through: :categorization
end

class Category
  has_many :categorizations
  has_many :products, through: :categorization
end

我想列出每个类别的前5个产品

但我无法找到一种方法来限制所包含的product。以下是我目前的疑问:

@categories = Category.includes(:products).all

我找到的唯一解决方案是在模型中添加条件,如:

# Solutions that I don't like
class Category
  ...
  has_many :products, include: product, limit: 5
end

有什么建议吗?感谢

2 个答案:

答案 0 :(得分:1)

如果在Product类上创建范围以返回前五个对象,则可以在关系上调用该范围。像这样:

class Product
  has_many :categorizations
  has_many :categories, through: :categorization

  scope :first_five, -> { limit(5) }
end

然后您可以执行以下操作:

@categories = Category.includes(:products)
@categories.each do |category|
  puts category.products.first_five.inspect
end

每个类别最多可以看到5种产品。

答案 1 :(得分:1)

<强>条件

你可以试试这个:

#app/models/product.rb
Class Product < ActiveRecord::Base
    has_many :categorizations
    has_many :categories, -> { limit(5) }, through: :categorization
end

如果你看"Eager Loading Of Associations",你可以看到这种想法的一个很好的演示


ActiveRecord Association Extensions

但是,我认为这只会产生5个类别。如果您希望每个类别使用5个,则还可以使用ActiveRecord Association Extenstions

#app/models/product.rb
Class Product < ActiveRecord::Base
    has_many :categorizations
    has_many :categories, through: :categorization do
        def first_five
            limit(5)
        end
    end
end

@categories = Category.includes(:products).all
@categories.each do |category|
    puts category.first_five
end