Rails收集路由一次删除多条记录

时间:2015-01-20 09:03:18

标签: ruby-on-rails rails-routing

我为remove_multiple创建了一个收集路径:

resources :myfiles do
  collection do
    delete 'remove_multiple' => 'myfiles#remove_multiple'
  end
end

以下是我的观点:

<%= form_tag remove_multiple_myfiles_path, method: :delete do %>
<table>
.....
<td><%= check_box_tag "myfile_ids[]", myfile.id %></td>
.....
</table>
<%= submit_tag "Delete all" %>
<% end %>

这是我的控制者:

before_action :set_myfile, :check_user, except: [:remove_multiple]

def remove_multiple
 @myfiles = Myfile.find(params[:myfile_ids])
 @myfiles.each do |myfile|
  myfile.destroy
 end
 flash[:notice] = "Deleted files!"
 redirect_to trashcan_path
end

但这是控制台所说的:

Started DELETE "/myfiles/remove_multiple" for ::1 at 2015-01-20     14:16:02 +0530
Processing by MyfilesController#destroy as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"VebaegOfVddyLiOs9oWP4DcLReC7ZPyttpKulIWMOMZN1JJ18T07aMirTSsqWkiDZOL8yMZ1iYi093tk4Qx4KQ==", "myfile_ids"=>["55", "56", "57"], "commit"=>"Delete all", "id"=>"remove_multiple"}
Myfile Load (0.3ms)  SELECT  `myfiles`.* FROM `myfiles` WHERE `myfiles`.`id` = 0 LIMIT 1
Redirected to http://localhost:3000/
Filter chain halted as :set_myfile rendered or redirected
Completed 302 Found in 5ms (ActiveRecord: 0.3ms)

为什么要执行Myfiles#destroy方法?即使我指定路线?

3 个答案:

答案 0 :(得分:1)

在您的routes.rb中:

resources :myfiles do
  collection do
    delete 'remove_multiple'
  end
end

#在您的视图中。

 # You are not passing the object id which you want to delete. 
 # see here, we are passing my_file.id in the path 
    <%= form_tag remove_multiple_myfiles_path(file_id: my_file.id), 
       method: :delete do %>
    <% end %> 

#my_files_controller.rb

#Exclude your remove_multiple action from any before_actions.
   def remove_multiple
     file_ids = params["myfile_ids"]
      Product.where(id: file_ids).destroy_all
   end

答案 1 :(得分:0)

你正在使用Rails 4吗?它看起来很好,但delete :remove_multiple应该比delete 'remove_multiple' => 'myfiles#remove_multiple'更清晰。首先运行rake routes,查看remove_multiple_myfiles_path映射到的内容。

答案 2 :(得分:0)

所以问题出在路线上。我不知道这是否特定于我的Rails应用程序或Rails本身,但路由不允许在集合中使用DELETE方法,而是保持重定向到默认的销毁操作。

所以我刚刚把我的remove_multiple路线作为POST。

collection do
  post 'remove_multiple' => 'myfiles#remove_multiple'
end