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
name
method does not exist on the user model. Particularly ifuser_id
is working. – Robin Fisher