sql - total of ratings when using letsrate gem -
i'm using letsrate gem (https://github.com/muratguzel/letsrate) allows users rate different attributes (called 'dimensions') of model (for eg "car" model can rated on "price" & "speed"). user allowed re-rate dimensions.
i display total sum value of ratings ie latest value of "price" plus latest value of "speed". total gets refreshed automatically every time user re-rates of dimensions.
after trial & error tried following helper method:
@rate_dimension_1 =rate.find_by_rater_id_and_rateable_id_and_dimension(@user.id, @object.id, "speed").stars @rate_dimension_2 = rate.find_by_rater_id_and_rateable_id_and_dimension(@user.id, @object.id, "price").stars total_rating = @rate_dimension_1 + @rate_dimension_2
but feel inefficient may want increase number of dimensions & sure slow way calculate when there many records. store total in db gets updated when of ratings changed.
what best way this?
i thinking add column rate db stores sum of dimensions. appreciate code summing latest values of dimensions per user per model id, storing & displaying via ajax?
first off, think better way going calculating total rating manually single query, rather 2 queries:
total_rating = rate.sum(:stars, conditions: {rater_id: @user.id, rateable_id: @object.id, dimension: %w(speed price)})
if want on all dimensions, can remove dimension
condition:
total_rating = rate.sum(:stars, conditions: {rater_id: @user.id, rateable_id: @object.id})
this leave single query db regardless of number of dimensions.
Comments
Post a Comment