Saving multiple records with a single form in Rails 4

后端 未结 3 690
忘了有多久
忘了有多久 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 14:58

    You want to use nested forms. You should be able to copy and paste the following code to get going:

    app/models/family.rb

    class Family < ActiveRecord::Base
      has_many :users
    
      accepts_nested_attributes_for :users
    end
    

    app/models/user.rb

    class User < ActiveRecord::Base
      belongs_to :family
    end
    

    app/views/families/new.html.erb

    <%= form_for(@family) do |f| %>
      <%= f.fields_for :users do |user| %>
        

    <%= user.text_field :name %>
    <%= user.text_field :email %>

    <% end %> <%= f.submit %> <% end %>

    app/controllers/families_controller.rb

      [...]
    
      def new
        @family = Family.new
        3.times { @family.users.build }
      end
    
      [...]
    
      private
        # Use callbacks to share common setup or constraints between actions.
        def set_family
          @family = Family.find(params[:id])
        end
    
        # Never trust parameters from the scary internet, only allow the white list through.
        def family_params
          params.require(:family).permit(:name, users_attributes: [ :name, :email ])
        end
    

提交回复
热议问题