Forum: Ruby on Rails Trying to pull data from ActiveRecord::Assosiation

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Gustavo Caso (Guest)
on 2014-04-14 11:19
(Received via mailing list)
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
But it always return all the sales.

sls = Sale.in_between( - 30,"ordered_on
@sales = do |sale|{ |l|  l.express_production }

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

Could anyone help me.
Frederick Cheung (Guest)
on 2014-04-14 16:33
(Received via mailing list)
On Monday, April 14, 2014 10:18:32 AM UTC+1, Gustavo Caso wrote:
> But it return every sale even when they have express_production = false.
> When none of a sale's line items have express_prodiction set to true

then{ |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
least one relevant line item.

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

Matt Jones (Guest)
on 2014-04-16 00:31
(Received via mailing list)
On Monday, 14 April 2014 05:18:32 UTC-4, Gustavo Caso wrote:
As Fred has pointed out, even when there aren't any matching line_items
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
Gustavo Caso (Guest)
on 2014-04-23 11:37
(Received via mailing list)

This topic is locked and can not be replied to.