繁体   English   中英

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

[英]Comments to Microposts: Create and Delete Comments in Rails ?

当我尝试删除注释时,出现错误“ nil:NilClass的未定义方法`destroy'”

当我向不同的微博添加评论时;所有评论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

microposts_controller.html.erb应该是app/controllers microposts_controller.rb 相同于static_pages_controller.html.erb

另外,在MicropostsController#show内部,您没有正确收到Micropost的注释。 您应该具有以下内容:

@comments = @micropost.comments

您现在正在做的是尝试使用微博ID获得特定评论,该ID很可能返回nil 这就是为什么您会得到destroy的错误的原因。

另一个问题可能是在_micropost.html.erb您将微_micropost.html.erb称为micropost @micropost ,而不是@micropost

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM