Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does using sum in a rails 3.1 scope result in an error?

I have this scope:

scope :total_quantity, sum('quantity')

When I run:

MyModel.total_quantity

I get this error:

NoMethodError: undefined method `default_scoped?' for 4:Fixnum

Running the sum method directly works

MyModel.sum('quantity') # 4

I can't find any documentation on the default_scoped? method, or why it is being called here. Do you know if there is a way to fix this problem?

like image 697
Nathan Manousos Avatar asked Sep 09 '11 18:09

Nathan Manousos


People also ask

What happens when you call a scope in rails?

As a result of calling a scope, you’ll get an ActiveRecord::Relation object. Which means you can chain & combine scopes! There’s more to learn about Rails scopes, so let’s keep exploring the topic.

How to query the database through models in rails?

In Rails, you can query the database through your models to access your data. You can do this using ActiveRecord methods. Like where, find, or find_by. As a result you get:

How to get the comment ID of a book in rails?

FROM "books" WHERE "books"."id" IN (1, 2, 3) You’ll find this query in the rails logs. If you’re looking to match based on an association value, you’ll have to make that association available with the joins method. With this query you get all the books, which have a comment, and the comment id is 2.

Can You chain&combine scopes in rails?

As a result of calling a scope, you’ll get an ActiveRecord::Relation object. Which means you can chain & combine scopes! There’s more to learn about Rails scopes, so let’s keep exploring the topic. When To Use Scopes?


1 Answers

Just try method instead of scope . It works like charm i also faced a same problem , but when i changed my scope to method its works fine . Below is working and tested code :)

def self.total_quantity
 sum('quantity')
end

Let me know if it works or not ! Thanks

like image 93
Vivek Parihar Avatar answered Sep 18 '22 23:09

Vivek Parihar