Reputation: 133
Using Ruby 2.3.3 and Rails 5.1.4
I have a form for users to fill out that uses the Nested Form Fields Gem to allow users to add a dynamic amount of Group Members. I would like to have the first instance already filled out and populated as current_user.email when the form is loaded
This is my class Group
class Group < ApplicationRecord
has_many :teammates, dependent: :destroy
accepts_nested_attributes_for :teammates, allow_destroy: true
end
This is my form
<%= form_with(model: group, local: true) do |form| %>
<div class="form-group row">
<%= form.nested_fields_for :teammates do |member| %>
<div align="right" class="col-md-3">
<label>Group Member: </label>
</div>
<div class="col-md-6">
<%= member.text_field :email, placeholder: 'email', class: 'input' %>
<%= member.remove_nested_fields_link %> <br />
</div>
<%end %>
<%= form.add_nested_fields_link :teammates, '+ Add a Group Member', id: 'addGroupMember' %>
</div>
Upvotes: 0
Views: 186
Reputation: 230531
Normally it's done like this
class GroupsController
def edit
@group.teammates.build(email: current_user.email)
end
end
You only build a teammate object, it's not being saved yet. But it's enough for the form to see it and render itself correspondingly.
Upvotes: 1