Reputation: 916
I'm making a website and it has articles and comments too, articles are not associated with users because only I as an admin can create articles...But there are the comments that are associated with users and articles too but when I try to show the username of the user that create the comment, in the comment section of an article it give me this error "undefined method `username' for nil:NilClass"
Models
User model
has_many :comments
Article model
has_many :comments
Comment model
belongs_to :article
belongs_to :user
Articles Controller where comments are shown
def show
@article = Article.find(params[:id])
@comments = @article.comments
end
and the view
<h2>Comments <%= @comments.count %></h2>
<% @comments.each do |comment| %>
<%= comment.content %>
<%= comment.user.username %>
<% end %>
Comments controller where comment is created
def create
@article = Article.find(params[:article_id])
@comment = Comment.new(comment_params)
@comment.article = @article
@comment.user = current_user
@comment.save
redirect_to article_path(@article)
end
Upvotes: 2
Views: 954
Reputation: 4893
You'd need a setup like the following:
# app/models/user.rb
class User < ActiveRecord::Base
has_many :articles
has_many :comments, through: :articles
end
# app/models/article.rb
class Article < ActiveRecord::Base
belongs_to :user
has_many :comments, dependent: :destroy
end
# app/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :article
belongs_to :user
end
rails g migration AddUsernameToUsers username:string:uniq
rails g migration AddUserIdToArticles user_id:integer
rails g migration AddArticleIdToComments article_id:integer
rails g migration AddUserIdToComments user_id:integer
rake db:migrate
This allows you to have a .username
method you can call on the User model, and allows for the following relation to return a proper username:
u = User.new(:username => "Foo")
u.save
a = Article.new(:user_id => 1)
a.save
comment = Comment.new(:article_id => 1, :user_id => 1)
comment.save
comment.user.username
# => "Foo"
Please note that if you're using Devise, you'd need to do something like:
rails g migration AddUsernameToUsers username:string:uniq
rake db:migrate
Upvotes: 2