2015-11-30 148 views
0

當我試圖刪除評論,我有一個錯誤,「未定義的方法'破壞」的零:NilClass」對Microposts的評論:在Rails中創建和刪除評論?

當我添加註釋,以不同的微觀柱;所有評論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 
+0

'microposts_controller.html.erb'應該在'app/controllers'裏面的'microposts_controller.rb'。 'static_pages_controller.html.erb'也一樣。 – linkyndy

+0

是的,你是對的。當我問了問題時,我寫錯了:) – Takor

回答

0

microposts_controller.html.erb應該microposts_controller.rbapp/controllersstatic_pages_controller.html.erb相同。

另外,在MicropostsController#show之內,您無法正確地收到Micropost的評論。你應該有這樣的事情:

@comments = @micropost.comments 

你現在正在做的是試圖讓使用ID微柱具體的評論,這更可能返回nil。這就是爲什麼你在destroy上得到錯誤。

另一個問題可能是您在_micropost.html.erb內部引用您的微博爲micropost而不是@micropost

+0

我已經在MicropostsController#show中刪除了「micropost = Micropost.find(params [:id])」,然後我得到了同樣的錯誤。之後我添加了「micropost = Micropost.find(params [:id])」和「comment = micropost.comments」來評論控制器的銷燬方法。現在該方法已完成,但註釋仍然存在,並且不會從數據庫中刪除。 @Andrei Horak – Takor

+0

如果您想在刪除微博時刪除所有評論,請將'dependent::destroy'添加到您的'Micropost has_many:comments'關聯中。 – linkyndy