I have a rating system for real estate agents. I have an agent model and an agent_review model. The rating is stored in the agent_review table, but I need to display the average rating in a view under the agent model and am running into some issue. All code is posted below, please and thank you in advance.
agent model:
has_many :agent_reviews
agent_review model:
belongs_to :agent
agent view:
<h3>Agent Rating: <%= @agent.agent_reviews.rating %> (<%= @agent.agent_reviews.count %>)</h3>
agent controller show method:
def show
@agent_reviews = AgentReview.all
@agent = Agent.find_by_slug(params[:id]) || Agent.find(params[:id])
if @agent.private_profile? && !current_agent&.super_admin?
redirect_to root_path, notice: "That user has a private profile"
else
@favorite_listings = @agent.liked_listings.available.includes(:neighborhood)
@agent_listings = @agent.sales_agent_listings.available.visible
@mate_posts = @agent.liked_mates.order(:when)
respond_to do |format|
format.html
format.json { render json: @agent }
end
end
end
error:
@agent.agent_reviews
is an Active Record relationship - there is no 'rating' for that, since it's more than one agent_review
object (the fact that it's plural should tell you that).
So if an agent has 6 reviews, with ratings that vary from 1 to 5, you want to show the average of those. You need to add the following to the agent.rb
model file:
def average_rating
if self.agent_reviews.any?
sum = 0
self.agent_reviews.each do |agent_review|
sum += agent_review.rating
end
return sum/self.agent_reviews.count
else
return nil # agent has no reviews, don't divide by zero!
end
end
(that's more verbose than it needs to be, you could condense it with some SQL magic)
And reference that new method in your view:
<h3>Agent Rating: <%= @agent.average_rating %> (<%= @agent.agent_reviews.count %>)</h3>