请帮忙。我刚学铁路。我需要在管理信息中心页面中管理所有网站的评论。但我无法删除链接。
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
视图/管理/ index.html.erb
<%= render @comments %>
视图/管理/ _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
答案 0 :(得分:1)
在您的路线中,rails会生成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