我想创建一条允许删除所有shares
的路线。 RESTful方式是使用动词DELETE
。如何创建指向以下内容的路由:
DELETE /shares
我尝试了路线:
resources :shares do
delete :on => :collection
end
但是这产生了一个错误,即rails无法将nil
转换为符号。
现在我有:
resources :shares do
delete 'delete_all', :on => :collection
end
编辑:我在控制器操作名称中输入了一个拼写错误,后一种方法有效,但生成的网址/shares/delete_all
不是非常RESTful。
如何删除_delete_all_部分?
答案 0 :(得分:13)
对于Rails 3,你可以这样做,并且分别有指向index和delete_all的资源丰富的GET / DELETE集合操作:
resources :shares do
delete :index, on: :collection, action: :delete_all
end
如果你正在使用Rails 4,你可以利用关注点干掉它并将其应用到许多资源中:
concern :deleteallable do
delete :index, on: :collection, action: :delete_all
end
resources :shares, concerns: :deleteallable
resources :widgets, concerns: :deleteallable
答案 1 :(得分:6)
我错过了什么?
match 'shares', :to => 'shares#delete_all', :via => :delete
更多信息:http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/
<subjective opinion>
这通常是一个坏主意和代码/设计气味。需要通过RESTful接口删除所有记录应该真正在受保护(经过身份验证)的操作后面和/或操作应该以某种方式限定用户。
答案 2 :(得分:2)
您的案例的正确方式,在路线中:
resources :shares, except: :destroy
resource :share, only: :destroy
请注意,我为破坏行动写了资源一词
然后在shares_controller中重新定义“destroy”:
def destroy
respond_to do |format|
if Share.destroy_all
format.html { redirect_to root_path, notice: 'Share collection successfully deleted' }
else
format.html { redirect_to root_path, notice: 'Share collection cannot be deleted.' }
end
end
end
答案 3 :(得分:1)
以下是非REST方式:
resources :shares do
collection do
delete :destroy_all
end
end
然后在你的控制器中你需要这样的东西:
def destroy_all
Share.delete_all
end
然后这就是你想要做的事情:
resources :shares do
collection do
delete :index
end
end
然后在你的控制器中你需要这样的东西:
def index
if request.method == delete #delete might need to be a string here, I don't know
Share.delete_all
else
@shares = Share.all
end
end
答案 4 :(得分:1)
至少在Rails 4.2中有一个稍微简单的语法:
<script>
function bar(){
//does something
};
function foo(){
$.ajax({
//options here
,complete: function(){
bar();
}
})
};
foo();
</script>
答案 5 :(得分:0)
resources :shares do
collection do
delete '/', :to => :delete_all
end
end