Could someone please explain why this works: current_user.accounts.sum(:balance) But not this: current_user.accounts.find_all_by_active(true).sum(:balance) For the latter Rails tells me sum is an undefined method. It seems like I lose the ActiveRecord methods when I call ''find''? This (simpler) does not work either: current_user.accounts.find_all.sum(:balance) Thanks! -- Posted via http://www.ruby-forum.com/.
One way: Account.sum(:balance, :conditions => "user_id = #{current_user.id} AND active = true") another way: Account.with_scope(:find => "user_id = #{current_user.id} AND active = true") do Account.sum(:balance) end On 8/15/06, Carl Johnson <carl_ivar@yahoo.com> wrote:> Could someone please explain why this works: > > current_user.accounts.sum(:balance) > > But not this: > > current_user.accounts.find_all_by_active(true).sum(:balance) > > For the latter Rails tells me sum is an undefined method. It seems like > I lose the ActiveRecord methods when I call ''find''? > > This (simpler) does not work either: > > current_user.accounts.find_all.sum(:balance) > > Thanks! > > -- > Posted via http://www.ruby-forum.com/. > _______________________________________________ > Rails mailing list > Rails@lists.rubyonrails.org > http://lists.rubyonrails.org/mailman/listinfo/rails >
Ray Baxter
2006-Aug-16 01:55 UTC
[Rails] Re: calculate method is gone once I use ''find''?
Carl Johnson wrote:> Could someone please explain why this works: > > current_user.accounts.sum(:balance) > > But not this: > > current_user.accounts.find_all_by_active(true).sum(:balance) > > For the latter Rails tells me sum is an undefined method. It seems like > I lose the ActiveRecord methods when I call ''find''? > > This (simpler) does not work either: > > current_user.accounts.find_all.sum(:balance)In the first case, you are calling the sum method on an ActiveRecord object. In the second case, you are calling sum on an array of ActiveRecord objects and as the error message tells you, the sum method is not defined for Array objects. The missing piece that you need to know is that when the finders return more than one ActiveRecord the results are returned in an array of ActiveRecords. You should be able to rewrite your first query current_user.accounts.sum(:balance, :conditions => [''active == ?'', true]) -- Ray
Carl Johnson
2006-Aug-16 02:22 UTC
[Rails] Re: calculate method is gone once I use ''find''?
Thanks, that helps!> You should be able to rewrite your first query > > current_user.accounts.sum(:balance, :conditions => [''active == ?'', > true])One question - where would be the best place for the above as far as MVC goes? Directly in the view or should I be setting a variable to the above in the controller? -- Posted via http://www.ruby-forum.com/.