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