在我的项目中,我有一个Organization
模型和一个Address
模型。以下是模型之间的关联:
class Organization < ApplicationRecord
has_one :address
accepts_nested_attributes_for :address
end
class Address < ApplicationRecord
belongs_to :organization
end
我在新的组织表单中添加了地址属性(Organization
属性的form_with和Address
属性的fields_for):
<%= 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 %>
当我试图用他的地址保存组织时,组织被保存但他的地址却没有。
如何保存组织的地址?
这是我的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
问题在于我的看法。我的表格没有包含我的field_for部分。
解决方案:
<%=form.field_for :address do |address_fields| %>
答案 0 :(得分:1)
belongs_to :address, optional: true
params.require(:organization).permit(:name,address_attributes: [:id,:city])