1
votes

I am trying to add dynamic fields to my rails application. I have a fields_for

<%= form.fields_for :books do |book| %>
    <%= render 'book_fields', form: book %>
<% end %>
<%= link_to_add_fields "Add Field", form, :books %>

When it renders book_fields I am getting the following error enter image description here

If I am passing form in render why would I be getting this error?

I have tried book.label :title but I get the same error but instead of the undefined varaible being form it is book. Any ideas? Thanks in advance.

UPDATE:

<%= form.fields_for :books do |builder| %>
  <%= form.label :title %>
  <%= form.text_field :title %>
  <%= form.hidden_field :_destroy %>
<% end %>

If I remove the partial render and stick the form text fields and labels into the fields_for itself it works. While rendering the partial, that is when I get the error.

1
Can you add more details, that book object should be a FormBuilder, maybe you're shadowing some variable. - Sebastian Palma
How can I check that? I'm sort of new to Rails. - Trenton Tyler
Does the fields_for work without rendering the partial, just "inline"? - Sebastian Palma
Yes. See question update. - Trenton Tyler
You're using the same outer variable outside in the fields_for block, try with builder instead form. - Sebastian Palma

1 Answers

1
votes

Instead using the form block variable as the local in your render method, you have to use the builder one, like:

<%= form.fields_for :books do |book| %> 
  <%= render 'book_fields', f: book %> 
<% end %> 

In the partial:

<fieldset> 
  <%= f.label :title %> 
</fieldset>

The error is happening because you're using your "main" form variable, and when the partial is being load, Rails try to find it as a local variable, which doesn't exist in that context.