因此,出于某种原因,我的代码似乎有自己的想法,并且会在某些点上工作,然后其他时候会在尝试在视图中运行此代码时抛出一个错误,说明未定义的名称方法
<%= div_for comment do %>
<p>
<big><%= h(comment.body) %> - <%= link_to comment.user.name, comment.user %> </big><br />
Posted <%= time_ago_in_words(comment.created_at) %> ago
</p>
<% end %>
我的评论控制器的代码如下所示
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(params[:comment])
@comment.user_id = current_user.id
@comment.save
respond_to do |format|
format.html { redirect_to @post}
format.js
format.json { render :json => @comments }
end
end
就像我说的那样,有时候这段代码运行正常,有时却没有。我不确定是什么导致了这个问题,更奇怪的是,在我的localhost中它的工作正常但是当我将代码推送到我的域时它不起作用。在您说它可能是域rails版本不匹配之前,您应该知道我的localhost之前已经发生过这个问题,然后在没有更改任何代码的情况下神奇地解决了。如果有人能帮助我,我将不胜感激。
编辑:这是您请求的错误日志
Completed 500 Internal Server Error in 286ms
ActionView::Template::Error (undefined method `name' for nil:NilClass):
1: <%= div_for comment do %>
2: <p>
3: <big><%= h(comment.body) %> - <%= link_to comment.user.name, comment.user.name %></big><br />
4: Posted <%= time_ago_in_words(comment.created_at) %> ago
5: </p>
6: <% end %>
app/views/comments/_comment.html.erb:3:in `block in _app_views_comments__comment_html_erb___3516162043769402279_2170426440__2165839557434581766'
app/views/comments/_comment.html.erb:1:in `_app_views_comments__comment_html_erb___3516162043769402279_2170426440__2165839557434581766 '
app/views/posts/show.html.erb:14:in `_app_views_posts_show_html_erb__667623582898069867_2171134300_136023206927572946'
app/controllers/posts_controller.rb:23:in `show'
答案 0 :(得分:0)
发生错误时,您可以签出comment.user的值。似乎comment.user不是您期望的对象User。检查您的数据库,可能有些评论与用户无关或与不存在的用户相关联。
如果再次出现错误,可以尝试进行此类调试:
<% comments.each do |comment| %>
<%= debug comment %> // Or comment.user
<% end %>