I have a model called Family that belongs
to user_ I want the user to be able to add multiple family members to the same form, which is located in /views/families/new.html.erb
EDIT: Sorry, I should have provided more verbose code earlier after a bit of code modification
In routes.rb resources: family EDIT: In User.rb
class User < ActiveRecord::Base
has_many :families
end
EDIT: At Family.rb
class Family < ActiveRecord::Base
belongs_to :user
end
In FamiliesController
def new
end
EDIT: I changed the form as follows:
<%= form_tag(controller: "families") do %>
<% i = 0 %>
<% 3.times do %>
<br>
<h2>Family Member
<br>
<%= fields_for("family[#{i}]") do |f| %>
<%= f.text_field :name, class: "form-control" , placeholder: "Name"%> <br>
<%= f.text_field :relationship, class: "form-control" , placeholder: "Relationship" %> <br>
<%= f.date_field :dob, class: "form-control" %> <br>
<%= f.text_field :blood_group, class: "form-control", placeholder: "Blood group" %> <br>
<%= f.text_field :email, class: "form-control", placeholder: "Email" %> <br>
<%= f.number_field :phone, class: "form-control", placeholder: "Phone number" %> <br>
<%= f.text_area :hobbies, class: "form-control", placeholder: "Hobbies" %> <br>
<% i=i+1 %>
<% end %>
<hr>
<% end %> <br>
<%= submit_tag "Submit", class: "btn btn-primary" %> <br>
EDIT: create an action in FamilyController
def create
@family = Family.new(family_params)
a = params[:family][:"0"]
@family.user_id = current_user.id
if @family.save
flash[:notice] = params[:family][:"0"]
redirect_to dummy_path
else
flash[:notice] = "didnt happen"
end
end
- Thus, the user sees a form for creating 3 family members for one user_id
- Enters data in 3 identical forms, and the images are sent
- 3 3 db
EDIT: , :
def family_params
params.require(:family).permit(:all)
end