对Microposts的评论:在Rails中创建和删除评论?

时间:2015-11-30 14:28:39

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

当我试图删除评论时,我有一个错误,"未定义的方法`destroy'为零:NilClass"

当我向不同的微博添加评论时;所有评论micropost_id都相同,并在所有微博下面显示所有评论。

如果有人帮助我添加评论微博,我将不胜感激。我已经尝试了两个星期这个问题而且我没有:(

create_comments.rb

   def change
     create_table :comments do |t|
         t.string :commenter_id
         t.text :body
         t.references :micropost, index: true, foreign_key: true
         t.timestamps null: false
      end

comments_controller.rb

def create
  micropost = Micropost.find_by(params[:id])
  @comment = micropost.comments.build(comment_params)
  @comment.commenter_id = current_user.id
  @comment.save
  redirect_to root_url
end

def destroy
  @comment.destroy
  flash[:success] = "Comment deleted"
  redirect_to request.referrer || root_url
end

_comment.html.erb

     <% @comment.each do |comment| %>
         <p><%= comment.body %></p>
         <span class="timestamp">
             Posted <%= time_ago_in_words(comment.created_at) %> ago.
             <%= link_to "delete", comment, method: :delete %>
         </span>
     <%end%>

_comment_form.html.erb

<%= form_for(Comment.new) do |f| %>
   <p>
     <%= f.text_area :body, :placeholder => "Leave a comment" %>
   </p>
   <p>
     <%= f.submit %>
   </p>
<% end %>

的routes.rb

resources :microposts  
resources :comments 

_micropost.html.erb

<li id="micropost-<%= micropost.id %>">
   <%= link_to micropost.user.name, micropost.user %>
   <%= micropost.content %>

    <div id="comments">
         <%= render "comments/comment" %>
    </div>
         <%= render 'shared/comment_form' %>

</li>

microposts_controller.html.erb

 def show
     @micropost = Micropost.find(params[:id])
     @comment = @micropost.comments(params[:id])
 end

static_pages_controller.html.erb

def home
 if logged_in?
   @micropost  = current_user.microposts.build
   @feed_items = current_user.feed.paginate(page: params[:page])
   @comment = Comment.all
 end
end

1 个答案:

答案 0 :(得分:0)

microposts_controller.html.erb microposts_controller.rb位于app/controllers内。 static_pages_controller.html.erb也一样。

此外,在MicropostsController#show内,您无法正确获取Micropost的评论。你应该有类似的东西:

@comments = @micropost.comments

您现在正在尝试使用微博ID来获取特定评论,这很可能会返回nil。这就是您在destroy上收到错误的原因。

另一个问题可能是_micropost.html.erb内部您将微博引用为micropost,而不是@micropost