Writing a Scope containing a method - Rails 4 -
i new rails , or advise appreciated
- i trying write scope displays users ratings equal or greater 4. unsure why scope not working , 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 when written this:
<% if user.average_rating_final_score >= 4 %> # display users ratings equal or greater 4 star <% end %>
but write in views
@users.ratings_equal_and_greater_than_4
could 1 kindly advise me how write correctly scope
rails scopes arel - kind of ruby wrapped sql. it's mean can't call ruby code sql statement this:
where('average_rating_final_score >= 4')
but can define class method work want:
def self.ratings_equal_and_greater_than_4 all.reject{ |record| record.average_rating_final_score < 4 } end
also can write propper sql query:
where('(`table_name.ratings_total` / `table_name.ratings_count`) >= 4')
Comments
Post a Comment