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?
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.
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:
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.
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With