如何在管理员评论控制器中创建评论的删除链接



请帮忙。我只是在学习轨道。我需要在管理仪表板页面中管理所有站点的评论。但我无法制作删除链接。

class Admin::CommentsController < ApplicationController
  def index
    @comments = Comment.all
  end
  def destroy
    @commentable = find_commentable
    @comment = @commentable.comments.find(comment_params)
    @comment.destroy
    if @comment.destroy
      flash[:success] = "Comment Destroyed!"
      redirect_to :back
   end
  end
  private
    def comment_params
        params.require(:comment).permit(:body, :user_id)
    end

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

views/admin/index.html.erb

<%= render @comments %>

views/admin/_comment.html.erb

<tr>
  <td><%= comment.body %></td>
    <td><%= link_to comment.user.name, comment.user %></td>
    <td><%= t(comment.commentable_type) %></td>
    <td><%= comment.commentable_id %></td>
    <td><%= link_to "edit"  %>
    | <%= link_to 'Delete', [:admin, comment], :confirm => "Are you sure?", :method => :delete %></td>
</tr>

在我的路线评论资源中:

  resources :users
  resources :sessions, only: [:new, :create, :destroy]
  resources :articles do
    resources :comments
  end
  resources :companies do
    resources :comments
  end
  resources :cabinets do
      resources :comments
  end
  namespace :admin do
    get '', to: 'dashboard#index', as: '/'
    resources :articles do
      resources :comments
    end
    resources :companies do
      resources :comments
    end
    resources :cabinets do
      resources :comments
    end
  end

从你的路线中,rail生成像admin_articles_comment(@article, @comment)这样的路径(相同:[:admin, @article, @comment]),所以如果你想要这样,你应该使用

link_to [:admin, comment.commentable, comment], method: :destroy, confirm: 'You sure?'

但这可能需要您在路由中指定控制器,或创建其他控制器(检查rake routes以查看路径指向的位置)

另一方面,您可以在路由中使用这样的shallow: true

namespace :admin do
    get '', to: 'dashboard#index', as: '/'
    resources :articles do
      resources :comments, shallow: true
    end
    resources :companies do
      resources :comments, shallow: true
    end
    resources :cabinets do
      resources :comments, shallow: true
    end
  end

它应该与您当前的设置(链接,控制器)一起使用(尽管我自己从未使用过),这里有一些信息:http://guides.rubyonrails.org/routing.html#shallow-nesting

最新更新