0

나는 부동산 중개인을위한 평가 시스템을 운영하고 있습니다. 에이전트 모델과 agent_review 모델이 있습니다. 등급은 agent_review 테이블에 저장되어 있지만 에이전트 모델의보기에 평균 등급을 표시해야하며 문제가 발생합니다. 모든 코드는 아래에 게시되어 있으므로 미리 알려 주시기 바랍니다.NoMethodError는 레일즈 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는 액티브 레코드의 관계는 - 더 이상의 agent_review 객체 (당신이 말해야 복수의 사실은)이기 때문에 그에 대한 '평가'는 존재하지 않는다.

상담원의 평점이 1에서 5까지 인 6 개의 리뷰가있는 경우 평균을 표시하려고합니다. 당신하여 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 
관련 문제