In my project, I have an Organization
model and an Address
model. Here is the association beetween the models:
class Organization < ApplicationRecord
has_one :address
accepts_nested_attributes_for :address
end
class Address < ApplicationRecord
belongs_to :organization
end
I added address attributes in my new organization form like this (form_with for Organization
attributes and fields_for for Address
attributes):
<%= form_with(model: organization, local: true) do |form| %>
<div class="field">
<%= form.label :organizationName %>
<%= form.text_field :organizationName, id: :organization_organizationName %>
</div>
<div class="field">
<%= form.label :email %>
<%= form.text_field :email, id: :organization_courriel %>
</div>
<div class="field">
<%= form.label :webSite %>
<%= form.text_field :webSite, id: :organization_webSite %>
</div>
<%= fields_for :adresse, organization.address do |address_fields| %>
Street number: <%=address_fields.text_field :streetNumber%><br>
Street: <%=address_fields.text_field :street%><br>
City: <%=address_fields.text_field :city%><br>
Province: <%=address_fields.text_field :province%><br>
Postal code: <%=address_fields.text_field :postalCode%><br>
<% end %>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
When I'm trying to save the orginization with his address, organization is saved but his address is not.
How do I save the address of the organization?
Here is my OrganizationController:
def new
@organization = Organization.new
@organization.build_address
end
def create
@organization = Organization.new(organization_params)
@organization.save
//...
end
def organization_params
params.require(:organization).permit(:organizationName, :email, :webSite, address_attributes:[:streetNumber, :street, :city, :province, :postalCode])
end
EDIT
The problem was my view. My form didn't include my field_for section.
Solution:
<%=form.field_for :address do |address_fields| %>