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

B2ea0545dc3b54e877f4a36be4fcde89?d=identicon&s=25 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
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
81b61875e41eaa58887543635d556fca?d=identicon&s=25 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     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
6883e5ef03484d4fcef507d7b4f1d243?d=identicon&s=25 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
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
B2ea0545dc3b54e877f4a36be4fcde89?d=identicon&s=25 Gustavo Caso (Guest)
on 2014-04-23 11:37
(Received via mailing list)

  
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.