Trying to pull data from ActiveRecord::Assosiation

I have a rails app, with sale which has_may :line_items. I’m trying to pull from the database if the line item are express_production.

But it always return all the sales.

sls = Sale.in_between(Date.today - 30, Date.today).order(“ordered_on DESC”)

@sales = sls.select do |sale|

sale.line_items.select{ |l| l.express_production }

end

But it return every sale even when they have express_production = false.

Could anyone help me.

Thanks

When none of a sale’s line items have express_prodiction set to true

then sale.line_items.select{ |l| l.express_production } will be , but that is still truthy to ruby so @sales will be set to all sales.

You could for example tack a .any? on the end to only select sales with at least one relevant line item.

You might also want to look into doing this filtering via the DB - at the moment you’ll be loading all of the line items for each sale (one sale at a time), which won’t be very fast.

Fred

As Fred has pointed out, even when there aren’t any matching line_items the inner select here will still return a truthy .

One way to do this with SQL might be: (I’m assuming express_production is a boolean column on the line_items table)

Sale.in_between(…).joins(:line_items).where(line_items: { express_production: true }).order(…)

This should generate an INNER JOIN clause between sales and line_items.

–Matt Jones

Thanks that really helped.