在嵌套表单中构建Rails嵌套表单

时间:2015-03-20 18:30:08

标签: ruby-on-rails ruby-on-rails-4 nested-forms

我有一个铁轨表格,其中包括父母,孩子和孩子的孩子。我正在使用nested_form gem,我的rails版本是4.1。我遇到的问题是嵌套表单,其中包含嵌套字段。我不希望用户使用按钮添加嵌套资源,但我希望在加载视图时实例化嵌套对象。

父模型

class LoanApplication < ActiveRecord::Base
  # Associations
  has_many :business_contacts, :dependent => :destroy

  # Nested Object 
  accepts_nested_attributes_for :business_contacts, :allow_destroy => true
end 

父母的孩子

class BusinessContact < ActiveRecord::Base
  # Associations
  belongs_to :loan_application
  has_one :personal_guarantee

  # Nested objects
  accepts_nested_attributes_for :personal_guarantee, :allow_destroy => true
end

孩子的孩子(孙子女)

class PersonalGuarantee < ActiveRecord::Base
  # Associations
  belongs_to :business_contact
end

查看

<%= f.fields_for :business_contacts, :wrapper => true do |contact_form| %>
    <%= contact_form.fields_for :personal_guarantee do |guarantee| %>
        <%= guarantee.text_field :guarantor_net_worth %>
    <% end %>
<% end %>

business_Contacts字段显示正常,但business_contacts的子节点未显示。我在loan_application_controller的params哈希中嵌套了personal_guarantee字段。

loan_application_controller.rb

def loan_applications_params
  params.require(:loan_application).permit(:loan_application_id, business_contacts_attributes: [:id, :business_salesforce_id, :prefix, :first_name, :exp_revenue_growth, :last_name, :business_title, :is_employee, :equity_hurdle, :contact_railsid, :guarantor_gender, :guarantor_sin_number, :guarantor_date_of_birth, :guarantor_phone_number, :guarantor_street_address, :guarantor_city, :guarantor_postal_code, :guarantor_province, :_destroy, personal_guarantee_attributes: [:id, :guarantor_net_worth]]
end

正如我上面提到的,通过上述设置,我无法在表单中看到PersonalGuarantee字段。

1 个答案:

答案 0 :(得分:0)

根据rails指南fields_for期望选项hash是第三个param,第二个是object或nil。请试试这个:

<%= f.fields_for :business_contacts, nil, :wrapper => true do |contact_form| %>

另外,我认为,表单中的所有对象都是构建的。