gpt4 book ai didi

ruby-on-rails - Rails 4 - 对包含的模型设置限制

转载 作者:行者123 更新时间:2023-12-03 15:52:45 24 4
gpt4 key购买 nike

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

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

有什么建议吗?谢谢

最佳答案

如果您在 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 个产品。

关于ruby-on-rails - Rails 4 - 对包含的模型设置限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22244859/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com