开发者

Buggy Comments Code with Rails App

So for some reason my code seems to have a mind of its own and will work at some points and then other times will throw an error saying undefined name method when trying to run this code in the view

  <%= 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 %>

The code for my comments controller looks like this

   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

Like I said sometimes this code works fine and sometimes it doesn't. I'm not sure whats causing the problem, whats even more weird is that in my localhost its working fine but when I push the code to my domain it doesn't work. Before you say it may be a domain rails version mismatch you should know this problem has occurred on my localhost as well before and then resolved itself magically without me changing any code. If anyone could help me it would be greatly appreciated.

Edit: Here is the error log you requested

 Completed 500 Internal Server Error in 286ms

 ActionView::Template::Error (undefined method `name' for nil:NilClass):
     1: <%= div_开发者_JAVA技巧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'


You may checkout the value of comment.user when the error occurs. It seems that comment.user is not an object User as you expect. Checkout your database, maybe some comments are not associated with users or associated with non-existant users.

You can try to debug like this when you'll have the error again:

<% comments.each do |comment| %>
  <%= debug comment %> // Or comment.user
<% end %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜