Search code examples
ruby-on-railspostgresqlactiverecordnomethoderror

NoMethodError Undefined Method FixNum - Rails 4


I have an agent_review model and an a agent model. In the agent_review table there is a column named "reviewer_id" and that is the id of the agent that reviewed the agent. I am having an issue getting the name of the reviewer from the id. I hope that makes sense. Below is the relevant code. Thanks in advance.

Agent model

has_many :agent_reviews

Agent_Review model

belongs_to :agent

Agent_Reviews Controller - Index Method

def index
   @agent = Agent.find(params[:agent_id])
   @agent_reviews = @agent.agent_reviews.order(created_at: :desc)
end

Agent_Review/Index

<div class="mega-container"><br>
   <div class="text-center">
      <h1>Agent Reviews</h1>
      <h3><%= @agent.name %></h3>
      <div class="container feedback-index">
         <% @agent_reviews.each do |agent_review| %>
            <div class="row feedback-strip">
               <p>Submitted: <%= agent_review.created_at.strftime('%D @ %I:%M %p') %></p>
               <p>Name: <%= agent_review.agent.name %></p>
               <p class="star-rating" data-score= <%= agent_review.rating %> >Rating: </p>
               <p>Review: <%= agent_review.comment %></p>
            </div><br>
         <% end %>
      </div>
    </div>
  </div>

Error

enter image description here

Schema

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

Solution

  • agent_review.reviewer_id returns a integer(Fixnum) and you can't call name method on a Fixnum object.

    And there's a problem with your association since you're not following the rails way of setting up foreign keys. First of all, you've to specify the column that you're using as a foreign key in agent_review model.

    # in agent_review.rb
    
    belongs_to :agent, foreign_key: 'reviewer_id'
    

    And then try

    <%= agent_review.agent.name %>
    

    to retrieve the name of the agent from the review.

    EDIT

    If you want to retrieve information about the reviewee, add a new association to agent_review.rb

    belongs_to :reviewee, class_name: 'Agent', foreign_key: 'agent_id'
    

    Now, you can call agent_review.reviewee which will give you information about the person who was reviewed.