Has_many有条件

时间:2016-11-28 10:46:38

标签: ruby-on-rails ruby

你好,我环顾四周,找不到答案。

我正在努力获得所有已批准的服装产品。我想这可以使用以下条件来完成:

has_many :approved_outfit_products, -> { where(approved: true) },
         class_name: 'TaggedProduct', dependent: :destroy

以下是一些额外信息:

outfit.rb

has_many :products, through: :outfit_products
has_many :approved_outfit_products, -> { where(approved: true) },
         class_name: 'TaggedProduct', dependent: :destroy
has_many :approved_products, through: :approved_outfit_products, source: :product, dependent: :destroy

Outfit.find(1).approved_products将返回已批准的产品列表。在这个产品列表中,我需要启用

要了解更好的信息,请访问rails c

$ rails c
PLoading development environment (Rails 4.2.0)
ro2.1.2 :001 > Product.new
 => #<Product id: nil, title: nil, description: nil, created_at: nil, updated_at: nil, user_id: nil, category_id: nil, size_description: nil, shipping_description: nil, price_in_cents: nil, enabled: true>
2.1.2 :002 > TaggedProduct.new
 => #<TaggedProduct id: nil, product_id: nil, outfit_id: nil, approved: false, created_at: nil, updated_at: nil, receiver_id: nil, requester_id: nil>

提前谢谢。

1 个答案:

答案 0 :(得分:3)

您可以链接where只需添加.where(enabled: true)

编辑:啊等等,你首先需要加入产品

这样:

joins(:product).where(product: {enabled: true})