如何在rails中保存包含另一个模型属性的模型?
在我的项目中,我有一个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| %>
belongs_to :address, optional: true
params.require(:organization).permit(:name,address_attributes: [:id,:city])
我希望能够每次与我的组织保存地址。在我的情况下地址不是可选的。 –
你可以改变它像组织有地址和地址belongs_to组织。? – shoaib
我只是做了它,我想我在这里的东西:https://stackoverflow.com/questions/34863818/rails-one-form-to-two-models?rq=1 –
其轨道的版本,您正在使用? – shoaib
Rails version 5.1.4 –
拼写错误'ApplicationRecord'。它是'ActiveRecord :: Base' – Cyzanfar