Rails Restful actions Index Put

前端 未结 2 586
日久生厌
日久生厌 2021-01-18 03:50

I have frequently run into the situation where I want to update many records at once - like GMail does with setting many messages \"read\" or \"unread\".

Rails encou

相关标签:
2条回答
  • 2021-01-18 04:01

    I often add collection-based update_multiple and destroy_multiple actions to an otherwise RESTful controller.

    Check out this Railscast on Updating Through Checkboxes. It should give you a good idea how to approach it, come back and add to this question if you run into troubles!

    0 讨论(0)
  • 2021-01-18 04:16

    I've run into a few situations like you describe. The first couple of times I've implemented form almost identical to the one you suggest.

    About the third time I hit this problem I realized that every item I'm updating has a common belongs_to relationship with something else. Usually a user. That's exactly the epiphany you need to make sense of this RESTfully. It will also help you clean clean up the form/controller.

    Don't think of it as updating a bunch of messages, think of it as updating one user.

    Here's some example code I've used in the past to highlight the difference. Assuming that we we want bulk operations on messages that belong to the current_user...

    As of rails 2.3 we can add

     accepts_nested_attributes_for :messages
    

    to the user model. Ensure messages_attributes is part of attr_accessible, or is not attr_protected.

    Then create the route:

     map.resources :users, :member => {:bulk_message_update, :method => :put}
    

    Then add the action to the controller. With AJAX capabilities ;)

     def bulk_message_update
       @user = User.find(params[:id])
       @user.update_attributes(params[:user])
       if @user.save 
         respond_to do |format|
           format.html {redirect}
           format.js {render :update do |page|
              ...
           } 
         end       
       else
         ....
     end 
    

    Then your form will look like this:

    <% form_for current_user, bulk_message_update_user_url(current_user), 
         :html => {:method => :put} do |f| %>
      <% f.fields_for :messages do |message| %>
        form for each message
      <% end %>
      <%= sumbit_tag %>
    <% end %>
    
    0 讨论(0)
提交回复
热议问题