0
votes

EDIT: undefined method `name' for nil:NilClass

I have my comments up and ready, but when I to display the comments user name I get a NoMethodError. When I replace comment.user.name with comment.user_id, I get a result, so what's going on here?

<% @comments.each do |comment| %>
    <div class="media">
        <div class"media-body"
            <h4 class="media-heading">
            <ul>
                <li><%= comment.body %> :by <%= comment.user.name> </li>
            </ul>
            </h4>
        </div>
    </div>
<% end %>

Here are the Post and Comment class Post < ActiveRecord::Base has_many :comments belongs_to :user belongs_to :topic

default_scope { order('created_at DESC') }

    validates :title, length: {minimum: 5}, presence: true
    validates :body, length: {minimum: 20}, presence: true
    validates :topic, presence: true
    validates :user, presence: true

end

class Comment < ActiveRecord::Base belongs_to :post belongs_to :user end


In a migration when I added users to comments in my most recent I added a user_id column thinking I could link id_s to names, but I look at how the ROR guide is associating users and comments.

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.string :commenter
      t.text :body
      t.references :post

      t.timestamps
  end

     add_index :comments, :post_id
  end
end

It's something like this, but I don't want anyone without a user_id commenting, so I have to get the user_id to pull up a name somehow.


Here are the models for user and comment

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable

  has_many :posts
  has_many :comment
    mount_uploader :avatar, AvatarUploader

 class Comment < ActiveRecord::Base
   belongs_to :post
   belongs_to :user
 end
2
What is the relationship between your models. Please add them in the question.Aaditi Jain
Can you post the error. A NoMethodError would indicate that the name method does not exist on the user model. Particularly if user_id is working.Robin Fisher
added my models to an edit aboveClyde Brown

2 Answers

2
votes

undefined method `name' for nil:NilClass

This means that no instance of User model has been assigned a comment, so:

  1. Verify that a User has been assigned to Comment

  2. Make sure that you have create user_id field for comment table, and declared belongs_to :user in the Comment model.

  3. Don't forget to migrate the new schema, if you aren't sure, just rerun it.

  4. When you've migrated validate the spec/dummy/db/schema.rb that the proper column has been added.

  5. Make sure that there are no attr_accessor/reader :name, or you haven't explicitly defined the #name method for the Comment model.

  6. If you are using the state machine, make sure that you have no :name event.

  7. In some cases Rails doesn't reload models, and (as far as I know) it never reloads the DB, forcely reload the Rails to make sure that model, and schemas are picked up, i.e. kill the server, and restart it again.

  8. To know where is the instance method #name of class Comment is defined, issue:

    Comment.instance_method(:name).source_location
    # => [".../gems/activerecord-~.~.~/lib/active_record/associations/builder/association.rb", ~~]
    

    The valid file is like the same: association.rb

  9. One yet reason, is for example in seeding, when you assigning a user to a comment, you assign just user_id, but in case a User with such #id does't exist, access to comment with be as follows:

    comment.user_id # => 5
    comment.user # => nil
    

    So you have to fix the situation when you are assigning #ids and not User records themselves.

0
votes

You have to add the association between the models. Looks like you missed it if I am not wrong. You have the user_id column in the comments table but the association should also be set up in the models

Comment Model

class Comment < ActiveRecord::Base
  belongs_to :user
end

Also if you want to get the comments from user model add the below code.

User Model

class User < ActiveRecord::Base
  has_many :comment
end

Hope it helps.