catmal
catmal

Reputation: 1758

Query records by class method

If I have a class method for a product returning its average rating, how do I query products with average_rating greater than a param I receive from frontend?

class Product < ApplicationRecord

def average_rating 
  ratings.sum(:rate) / ratings.count
end

end

For a scope I would need to pass the param from controller to model. Should I do that? Or should I just calculate the average rating in the controller instead? Or save average_rating in database with a callback when a rating is saved?

Upvotes: 0

Views: 748

Answers (2)

Eyeslandic
Eyeslandic

Reputation: 14900

You cannot call class methods from SQL. You can however load all records into memory and do this, which is quite inefficient if you have a lot of records.

Product.all.select { |record| average_rating > record.value }

Upvotes: 2

Igor Kasyanchuk
Igor Kasyanchuk

Reputation: 774

If this is a ruby method you can't do it (with SQL), unless you move your "average" logic into SQL too.

If the amount of records is a small one of the simplest solution is to use Ruby.

Product.all.select{|e| :&average_rating > e.value}

Upvotes: 1

Related Questions