Saving multiple records with a single form in Rails 4

后端 未结 3 691
忘了有多久
忘了有多久 2020-12-30 14:23

I have a model called Family, which belongs_to User I want to enable the user to add multiple family members in a single form, which is in

3条回答
  •  长发绾君心
    2020-12-30 15:00

    The way that i always do this is to make a new action update_multiple. This expects params with the following structure (using your Family example, and updating two records, with ids 123 and 456)

    params = {:families => {123 => {:name => "foo", :address => "bar"}, 456 => {:name => "baz", :address => "qux"} }}
    

    and the action works like so:

    @families = []
    params[:families].each do |id, attributes|
      if family = Family.find_by_id(id)
        family.update_attributes(attributes)
        @families << family
      end
    end
    

    In order to set up the params with the required structure, your form would be set up like so:

    <% @families.each do |family| %>
      
    <% end %>

    You could, instead of making a new action, change the structure of your update action to do the standard code if it gets params[:family] and the above code if it gets params[:families].

提交回复
热议问题