I'm trying to calculate the average star rating of a movie object in my rails app using raty.js. Here's a snippet of my code:
controllers/movies_controller.rb
def show
@avg_review = @movie.average(:rating)
end
private
def set_movie
@movie = Movie.find(params[:id])
end
schema.rb
create_table "movies", force: true do |t|
t.integer "user_id"
t.string "title"
t.text "description"
t.integer "image_id"
t.string "director"
t.float "rating"
t.integer "num_ratings"
t.datetime "created_at"
t.datetime "updated_at"
t.text "url"
t.string "tracking"
end
I keep getting the error:
undefined method `average' for #<.Movie:0x5b385d0>
From my understanding, this is a predefined method in rails. Yet, I'm getting the error. Can someone help me?
From the docs you referenced, average
is meant to be called on the Movie
model itself, not an instance of it.
This will return the average of the column.
@avg_review = Movie.average(:rating)
You can also add conditions to the query (I made up a column for demonstration purposes):
# Get average of movie ratings from 2015
@avg_review = Movie.average(:rating).where(year: '2015')