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
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