2017-10-14 121 views
0

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

其轨道的版本,您正在使用? – shoaib

+1

Rails version 5.1.4 –

+0

拼写错误'ApplicationRecord'。它是'ActiveRecord :: Base' – Cyzanfar

回答

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

我希望能够每次与我的组织保存地址。在我的情况下地址不是可选的。 –

+0

你可以改变它像组织有地址和地址belongs_to组织。? – shoaib

+0

我只是做了它,我想我在这里的东西:https://stackoverflow.com/questions/34863818/rails-one-form-to-two-models?rq=1 –

相关问题