4

我想在我的評論控制器寫我的刪除方法。我的評論模型與其他模型具有多態關聯,但在這種情況下,我們只關注旅行。換句話說,@trip = @commentable。無法重定向到無評論控制器#銷燬(多態協會)

該評論被刪除就好了,但我不斷收到錯誤ActionController::ActionControllerError in CommentsController#destroy: Cannot redirect to nil!當我redirect_to @commentable這將是評論屬於的旅程。

我也在我的創建動作(評論控制器)中重定向到@commentable,並且在用戶創建新評論時工作得很好。

任何提示?

視圖(人次/ show.html.erb)

<% if [email protected]? %> 
    <% @commentable.comments.each do |comment| %> 
    <!-- Content --> 
    <%= link_to comment, :method => :delete do %> delete <% end %> 
    <% end %> 
<% end %> 

評論的形式,對創建工作的行動

<%= form_for [@commentable, Comment.new] do |f| %> 
    <%= f.text_area :content %> 
    <div id="comment_submit_button"><%= f.submit "Comment" %></div> 
<% end %> 

trips_controller.rb

def show 
    @trip = @commentable = Trip.find(params[:id]) 
    @comments = Comment.all 
end 

comments_controller.rb

def create 
    @commentable = find_commentable 
    @comment = @commentable.comments.build(params[:comment]) 
    @comment.user_id = current_user.id 

    if @comment.save 
    redirect_to @commentable 
    end 
end 

def destroy 
    # @commentable = find_commentable this line was wrong 
    @comment = Comment.find(params[:id]) 
    @commentable = @comment.commentable #this line fixed it 
    if @comment.destroy 
    redirect_to @commentable 
    end 
end 


def find_commentable 
    params.each do |name, value| 
    if name =~ /(.+)_id$/ 
     return $1.classify.constantize.find(value) 
    end 
    end 
nil 
end 

回答

4

找出解決方案。將上面的代碼發佈解決方案。

def destroy 
    @comment = Comment.find(params[:id]) 
    @commentable = @comment.commentable 
    if @comment.destroy 
    redirect_to @commentable 
    end 
end