I have the classes Person and Fingerprint and I want to work with nested forms in order to fill Fingerprint's attributes.
The implementation is as follows:
class Person < ApplicationRecord
belongs_to :fingerprint
end
class Fingerprint < ApplicationRecord
end
Person's controller:
def create
@person = Person.new(person_params)
@person.build_fingerprint
respond_to do |format|
if @person.save
....
end
def person_params
params.require(:person).permit(:name, fingerprints_attributes: [:fingertips_category])
end
Person's form:
%= form_with(model: person) do |form| %>
...
<div>
<%= form.label :name, style: "display: block" %>
<%= form.text_area :name %>
</div>
<%= form.fields_for :fingerprint do |fingerprint_form| %>
<%= fingerprint_form.label :fingertips_category %>
<%= fingerprint_form.text_field :fingertips_category %>
<% end %>
<div>
<%= form.submit %>
</div>
<% end %>
Unfortunately, I don't get how to initialize the Fingerprint's attributes with the help of build_fingerprint method.
There's nothing about it being a
belongs_toassociation that means you can't useaccepts_nested_attributes_for :fingerprintjust like ahas_*association.Only thing is that you need
fingerprint_attributes(notfingerprints...plural) in yourpermitcall. So then in thecreateyou'd just have the@person = Person.new(person_params)and then@person.save. You haven't shown it here but in yournewaction you would need to instantiate thefingerprintin the@personrecord you're using in the form.