在我的項目中,我有一個Organization
模型和一個Address
模型。這是該協會beetween型號:如何在rails中保存包含另一個模型屬性的模型?
class Organization < ApplicationRecord
has_one :address
accepts_nested_attributes_for :address
end
class Address < ApplicationRecord
belongs_to :organization
end
我加入我的新組織形式的地址屬性,像這樣(form_with爲Organization
屬性和fields_for爲Address
屬性):
<%= 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| %>
其軌道的版本,您正在使用? – shoaib
Rails version 5.1.4 –
拼寫錯誤'ApplicationRecord'。它是'ActiveRecord :: Base' – Cyzanfar