0

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?

sawa
  • 165,429
  • 45
  • 277
  • 381
adventuredoge
  • 345
  • 5
  • 17

2 Answers2

7

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')
sjagr
  • 15,983
  • 5
  • 40
  • 67
1

According to the average method documentation. it's a method for ActiveRecord::Calculations so you should use it on ActiveRecord collections or on the model directly, but you trying to use it on instance:

Wrong:

@avg_review = @movie.average(:rating)

Right:

@avg_review = Movie.average(:rating)
Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103