【发布时间】:2016-08-09 05:57:36
【问题描述】:
我已经为此工作了好几个小时,并且已经开始多次(从备份点)试图找出问题。
我正在尝试将 cmets 添加到帖子中。评论工作正常,它让用户名和头像显示不工作。这是我一步一步做的。
1) rails g model Comment body:text user:references post:references
2) 我验证了模型是正确的
class Comment < ApplicationRecord
belongs_to :user
belongs_to :post
end
3)rake db:migrate
4) 在 user.rb 和 post.rb 中添加了has_many :comments, dependent: :destroy
5) 在我的路线中添加了resources :comments。
resources :posts do
resources :comments
member do
post '/like' => 'posts#like'
end
end
6) 生成的cmets控制器rails g controller comments
7) 更改了 cmets 控制器:
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment].permit(:body))
@comment.user = current_user
if @comment.save
redirect_to post_path(@post)
else
# something else
end
end
end
8) 在 cmets 的视图文件夹中创建了两个部分“_comment.html.erb”和“_form.html.erb”。
“_comment.html.erb”
<h2><%= @comment.user.name %></h2>
<p><%= comment.body %></p>
“_form.html.erb”
<%= form_for([@post, @post.comments.build]) do |f| %>
<p>
<%= f.text_field :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
9) 将 cmets 添加到帖子的显示页面
<h4><%= @post.comments.count %> comments</h4>
<%= render @post.comments %>
<h2>Add a comment</h2>
<%= render "comments/form"%>
10) 重启服务器
11) 尝试创建评论并得到以下错误:
帖子中的NoMethodError#show
nil:NilClass 的未定义方法“用户”
<h2><%= @comment.user.name %></h2> #THIS LINE IS THE ERROR
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3