activerecord - Rails - undefined method `username' for nil:NilClass -


i'm making website , has articles , comments too, articles not associated users because admin can create articles...but there comments associated users , articles when try show username of user create comment, in comment section of article give me error "undefined method `username' nil:nilclass"

models

user model

has_many :comments 

article model

has_many :comments 

comment model

  belongs_to :article   belongs_to :user 

articles controller comments shown

def show     @article = article.find(params[:id])     @comments = @article.comments end 

and view

<h2>comments <%= @comments.count %></h2>     <% @comments.each |comment| %>         <%= comment.content %>         <%= comment.user.username %>     <% end %> 

comments controller comment 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 

you'd need setup 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 have .username method can call on user model, , allows following relation return proper username:

u = user.new(:username => "foo") u.save = article.new(:user_id => 1) a.save comment = comment.new(:article_id => 1, :user_id => 1) comment.save  comment.user.username # => "foo" 

please note if you're using devise, you'd need like:

rails g migration addusernametousers username:string:uniq rake db:migrate 

Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -