Reputation: 1799
i am new to rails and any help or advise would be much appreciated
user.rb
scope :ratings_equal_and_greater_than_4, where('average_rating_final_score >= 4')
def average_rating_final_score
if self.average_rating_score == 1.0
1
elsif self.average_rating_score == 2.0
2
elsif self.average_rating_score == 3.0
3
elsif self.average_rating_score == 4.0
4
elsif self.average_rating_score == 5.0
5
else
self.average_rating_score
end
end
def average_rating_score
ratings_total.to_f / ratings_count
end
the scope works well when written like this:
<% if user.average_rating_final_score >= 4 %>
# display users with ratings equal to or greater than 4 star
<% end %>
but i would like to write something like this in my views
@users.ratings_equal_and_greater_than_4
could one kindly advise me how to write this correctly as a scope
Upvotes: 1
Views: 31
Reputation: 1526
Rails scopes is the AREL - a kind of ruby wrapped sql. It's mean you can't call ruby code from SQL WHERE statement like this:
where('average_rating_final_score >= 4')
But you can define class method that will work as you want:
def self.ratings_equal_and_greater_than_4
all.reject{ |record| record.average_rating_final_score < 4 }
end
Also you can write propper SQL query:
where('(`table_name.ratings_total` / `table_name.ratings_count`) >= 4')
Upvotes: 2