Bezzi Bezzi - 7 months ago 23
Ruby Question

How to access a property from belongs_to model from a scope

I have 2 models in my app: Person and Review each person has many reviews and each review belongs to a person. I have an attribute called

grade
inside of my review model and I'd like to display the average grade of each person so I wrote this scope:

scope :average_grade, -> { self.first.review.average(:grade) }


Is there a better way for doing that? Besides the 2 queries that this method needs, I also have to run another 2 queries to get the proper Person object in my controller:

def show
@average = Person.includes(:review).where(id: params[:id]).average_grade
@person = Person.includes(:review).find(params[:id])
end


How could I avoid all of those queries?

Answer

Your scope is an instance method rather than scope, since it does not return ActiveRecord::Relation object.

I suggest you to do following:

# person.rb:
def average_grade
  review.average(:grade)
end

# controller:
def show
  @person =  Person.find(params[:id])
  @average = @person.average_grade
end
Comments