Bezzi Bezzi - 2 years ago 69
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

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, -> { }

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])

How could I avoid all of those queries?

Answer Source

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

# controller:
def show
  @person =  Person.find(params[:id])
  @average = @person.average_grade
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download