没有方法错误 - 从表中获取名称

时间:2016-11-09 21:34:39

标签: ruby-on-rails model-view-controller schema

我有一个代理和agent_review模型,我正在尝试创建一个页面,其中所有评论都可以在同一页面上访问。我正在解决正在审核的代理人和审核人姓名的问题。

ERB:

<div class="mega-container">
  <%= render 'matrix/listings/matrix_navigation' %>
    <div class="standard-page-header">
      <h1>Agent Reviews</h1><br>
      <hr>
    </div>
    <div class="text-center">
      <div class="container feedback-index">
        <% @agent_reviews.each do |agent_review| %>
          <div class="row feedback-strip">
            <h3>Agent Name: <%= agent_review.agent.name %></h3>
            <p>Review: <%= agent_review.comment %></p>
            <p>Star Rating: <%= agent_review.rating %> of 5</p>
            <p>Reviewer: <%= agent_review.reviewer.name %></p>
            <p>Submitted: <%= agent_review.created_at.strftime('%D @ %l:%M%p') %></p>
          </div>
        <% end %>
      </div>
    </div>
  </div>

架构:

create_table "agent_reviews", force: :cascade do |t|
  t.integer  "agent_id"
  t.integer  "reviewer_id"
  t.text     "comment"
  t.integer  "rating"
  t.datetime "created_at",  null: false
  t.datetime "updated_at",  null: false
end

控制器:

def all_reviews
  @agent_reviews = AgentReview.all
end

型号:

class Agent < ActiveRecord::Base
  has_many :agent_reviews
end

class AgentReview < ActiveRecord::Base
  belongs_to :agent, foreign_key: 'reviewer_id'
end

2 个答案:

答案 0 :(得分:1)

在您的AgentReview模型中:

belongs_to :reviewer, :class_name => 'Agent', :foreign_key => 'reviewer_id' 
belongs_to :agent, :class_name => 'Agent', :foreign_key => 'agent_id'

答案 1 :(得分:0)

您似乎错过了AgentReview

上的关联
class AgentReview < ActiveRecord::Base
  belongs_to :reviewer, class_name: "Agent", foreign_key: 'reviewer_id'
  belongs_to :agent
end