Hari Prakash Hari Prakash - 4 months ago 17
Ruby Question

Rails nested form display fields in index page along with parent form

index.html.haml

I have a customer details form which has a nested form named 'goods address'. I want to display all the customer details in index page.



%tbody
- @customer_details.each do |customer|
%tr
%td= customer.customer_name
%td= customer.customer_id
%td= customer.address
%td= customer.state
%td= customer.email





nested form


= fields_for customer_detail do |f|
= f.fields_for :goods_address do |t|
.fieldset
.row
.col-sm-12
= t.label :delivery_address,"Goods to be delivered at same address mention above?", class: "col-sm-6 control-label text-right"
= t.check_box :delivery_address, autofocus: true, class: "toggle-two customer-goods col-sm-6", :value => "On"
%br
%div{id: 'customer_goods'}
.main-center-pan.main-login-pan
.fieldset
.row
.col-sm-12
= t.label :name,"Name", class: "col-sm-3 control-label text-right"
= t.text_field :name, autofocus: true, class: "col-sm-3"
= t.label :contact_no,"Contact number", class: "col-sm-3 control-label text-right"
= t.text_field :contact_no, autofocus: true, class: "col-sm-3"
%br





parent form


= nested_form_for(@customer_detail) do |f|
- all_views_side_error_messages!(@customer_detail)
.form-alignment
.fieldset
.row
.col-sm-12
= f.label :customer_name,"Organisation/Customer Name", class: "col-sm-3 control-label text-right"
= f.text_field :customer_name, autofocus: true, class: "col-sm-3"
= f.label :residential_type,"Residential Type", class: "col-sm-3 control-label text-right"
= f.check_box :residential_type, autofocus: true, "data-width" => "200", class: "toggle-two-resident select-resident col-sm-3"
%br





The problem is I dont know how to define the nested form's fields in the index.can someone plz help me.Thanks in advance.

Answer

If you want to display the child-attributes(goods_address) with parent(customer_details), just loop the association of the parent object.

%tbody
- @customer_details.each do |customer|
  %tr
    %td= customer.customer_name
    %td= customer.customer_id
    %td= customer.address
    %td= customer.state
    %td= customer.email
    - if customer.goods_address.present?
        %td= customer.try(:goods_address).try(:delivery_address)
        %td= customer.try(:goods_address).try(:name)
        %td= customer.try(:goods_address).try(:contact_no)
Comments