如何在rails中保存包含其他模型属性的模型?

时间:2017-10-14 21:29:15

标签: ruby-on-rails model save associations

在我的项目中,我有一个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| %>

1 个答案:

答案 0 :(得分:1)

 belongs_to :address, optional: true
params.require(:organization).permit(:name,address_attributes: [:id,:city])