infinity
infinity

Reputation: 719

Part of form not showing issue

I have a rails 4 app where I'm following basically this railscast:

_form.html.erb:

<%= form_for @store, do |f| %>

   <%= f.fields_for :products do |builder| %>
      <%= render "product_fields",  f: builder %>
   <% end %>
   <%= link_to_add_fields "Add Product", f, :products  %>
<% end %>

_product_fields.html.erb

<%= f.select :the_product_type, %w[Shelves, Tools, Wires]%>
<div>
   <%= f.fields_for :product_fields do |builder| %>
      <%= builder.text_area :name_of_product_field %>
   <% end %>
</div>

My JS looks like:

$('form').on('click', '.add_fields', function(e) {
    var regexp, time;
    time = new Date().getTime();
    regexp = new RegExp($(this).data('id'), 'g');
    $(this).before($(this).data('fields').replace(regexp, time));

    return e.preventDefault();
 });

My issue is that when I click the Add Product button, I can only see a select. I can't see the name_of_product_field textarea. But I can't figure out why I can see the select if I can't see the textarea?

Upvotes: 0

Views: 35

Answers (1)

Kirti Thorat
Kirti Thorat

Reputation: 53038

product_fields is a nested attribute which you have not build anywhere in your code which is why you are not seeing it.

Assuming that a product has_many product_fields, you can resolve this issue in two ways, choose one that suits you:

1. Build it at Controller level

Build the product_fields in the Controller#action which is rendering the problematic view:

def action_name
  @store = Store.new
  product = @store.products.build
  product.product_fields.build
end

2.Build it at View level

Update the fields_for in _product_fields.html.erb as below:

<%= f.fields_for :product_fields, f.object.product_fields.build do |builder| %>

Upvotes: 1

Related Questions