Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Rails ActiveRecord to Query Unsaved Objects

Is it possible to query unsaved changes using Rail's ActiveRecord or another similar approach?

An example of a Ruby interactive session is below. What I'd like to see, is the fourth line show a result of '999' instead of '10'. I'm use to using .NET and Entity Framework where something similar to this was possible. Perhaps in Ruby there is a better or different way to do the same thing. I could obviously add up the sum in a loop, but I find the query syntax more elegant. Any help is appreciated.

i = Inventory.where(:product_id => 1)
i.sum(:available) => 10
i.first.available = 999
i.sum(:available) => 10
like image 598
kstevens715 Avatar asked Nov 16 '11 17:11

kstevens715


1 Answers

No, since sum() is actually translated to SQL and run on the db, you must save the record to the db in order for the query to return the result you want.

Alternatively, you can use the Enumerable#sum method in ActiveSupport, which takes a block, like so:

all = Inventory.where(:product_id => 1).to_a
all.first.available = 999
all.sum(&:available)
like image 114
Tim Morgan Avatar answered Oct 22 '22 12:10

Tim Morgan