0

我有一个针对房地产经纪人的评级系统。我有一个代理模型和一个agent_review模型。评分存储在agent_review表中,但我需要在代理模型下的视图中显示平均评分,并且遇到了一些问题。所有代码都张贴在下面,请提前谢谢。NoMethodError与Rails 4中的两个模型一起工作4

代理模型:

has_many :agent_reviews 

agent_review模型:

belongs_to :agent 

代理视图:

<h3>Agent Rating: <%= @agent.agent_reviews.rating %> (<%= @agent.agent_reviews.count %>)</h3> 

代理控制器显示方法:

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 

错误:

enter image description here

+0

显示从您的终端完整的错误日志 – luissimo

回答

1

@agent.agent_reviews是Active Record的关系 - 没有“评级”来表示,因为它比一个agent_review对象(事实上,它是复数应该告诉你)。

因此,如果一个代理人有6条评论,评分从1到5不等,您想要显示这些评分的平均值。您需要添加以下到agent.rb模型文件:

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 

(这是更详细的比它需要的是,你可以用一些SQL魔力凝结成)

和参考,在新方法你的看法:

<h3>Agent Rating: <%= @agent.average_rating %> (<%= @agent.agent_reviews.count %>)</h3> 
+0

完美的工作。谢谢! –

2

添加到Jhon Feltz的答案,你可以在一个短的模式下做到这一点。像这样:

def average_rating 
    agent_reviews = self.agent_reviews 
    agent_reviews.any? ? (agent_reviews.map(&:rating).sum/agent_reviews.count) : nil 
end