我有三个模特
class Property < ActiveRecord::Base
has_many :contact
accepts_nested_attributes_for :contact
has_many :business
accepts_nested_attributes_for :business
end
class Business < ActiveRecord::Base
belongs_to :property
has_many :contact
end
class Contact < ActiveRecord::Base
belongs_to :property
belongs_to :business
end
我创建了一个使用嵌套联系人和嵌套业务创建Property的表单,如何让该业务与嵌套联系人建立?
这是我的表格
<%= form_for(@property) do |f| %>
<div class="field">
<%= f.label :address %><br>
<%= f.text_field :address %>
</div>
<% end %>
<%= f.fields_for :contact do |contact_form| %>
<div class="field">
<%= f.label :contact_title, "Title" %><br>
<%= contact_form.text_field :title %><br>
<%= f.label :contact_name, "Name" %><br>
<%= contact_form.text_field :name %><br>
</div>
<% end %>
<%= f.fields_for :business do | business_form| %>
<div class="indv-biz field">
<%= f.label :business_name, "Name" %><br>
<%= business_form.text_field :name %><br>
</div>
<div class="business-contact">
<p>Business Contact</p>
<%= f.fields_for :business_contact do | business_contact | %>
<div class="field">
<%= business_contact.label :contact_title, "Title" %><br>
<%= business_contact.text_field :title %><br>
<% end %>
<% end %>
我可以保存,以便业务连接到该属性,并且联系人已连接到该属性,但我无法弄清楚如何将联系人连接到该业务
由于
答案 0 :(得分:2)
你应该像this一样尝试深度嵌套。您的要求是拥有许多业务的财产,而这些业务又有很多联系方式。在这种情况下,您实际应该做的是为业务设置属性的嵌套表单,并且该业务应该具有嵌套的联系人形式。下面的一个适合你。
<强>表格强>
nested_form_for @property do |f|
...
f.fields_for :bussiness do |bussiness_form|
...
bussiness_form.fields_for :contact_form do |contact_form|
....
end
end
end
end
<强>模型强>
class Property < ActiveRecord::Base
has_many :contact
has_many :business
accepts_nested_attributes_for :business
end
class Business < ActiveRecord::Base
belongs_to :property
has_many :contacts
accepts_nested_attributes_for :contacts
end
class Contact < ActiveRecord::Base
belongs_to :property
belongs_to :business
end
<强>控制器强>
def property_params
params.require(:property).permit(:id,.., :bussiness_attributes => [:id,.., , :contacts_attributes => [:id, ..]])
end