我正在制作一个网站,它也有文章和评论,文章与用户无关,因为只有我作为管理员才能创建文章...但是也有与用户和文章相关联的评论,但是当我尝试显示创建评论的用户的用户名,在文章的评论部分,它给了我这个错误“undefined method `username' for nil:NilClass”
型号
用户模型
has_many :comments
文章模型
has_many :comments
评论模型
belongs_to :article
belongs_to :user
显示评论的文章 Controller
def show
@article = Article.find(params[:id])
@comments = @article.comments
end
和 View
<h2>Comments <%= @comments.count %></h2>
<% @comments.each do |comment| %>
<%= comment.content %>
<%= comment.user.username %>
<% end %>
创建评论的评论 Controller
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
最佳答案
您需要进行如下设置:
# 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
这允许您拥有可以在 User 模型上调用的 .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"
请注意,如果您使用 Devise,则需要执行以下操作:
rails g migration AddUsernameToUsers username:string:uniq
rake db:migrate
关于ruby-on-rails - Rails - 未定义方法 `username' for nil :NilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32301190/