joeyk16 joeyk16 - 1 year ago 101
Ruby Question

Has_many with condition

Hello i have looked around and can't find an answer.

I am trying to get all the approved products that are enabled for an outfit. Im thinking this can be done using a condition here:

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

Here is some extra info:


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 will return me a list of products that have been approved. Out of this list of products i need the ones that have been enabled.

To understand what is going on better here is rails c

$ rails c
PLoading development environment (Rails 4.2.0)
ro2.1.2 :001 >
=> #<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 id: nil, product_id: nil, outfit_id: nil, approved: false, created_at: nil, updated_at: nil, receiver_id: nil, requester_id: nil>

Thank you in advance.

Answer Source

You can chain wheres just add a .where(enabled: true)

Edit: ah hold on, you first need to join with products


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download