NoMethodError 在 Rails 4 中使用两个模型

NoMethodError working with two models in Rails 4

我有一个房地产经纪人评级系统。我有一个代理模型和一个 agent_review 模型。评分存储在 agent_review table 中,但我需要在代理模型下的视图中显示平均评分并且 运行 遇到了一些问题。所有代码贴在下面,请提前谢谢。

代理模型:

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

错误:

@agent.agent_reviews 是一种 Active Record 关系 - 没有 'rating',因为它不止一个 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>

添加到 John Feltz 答案中,您可以在简短模式下执行此操作。像这样:

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