1

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.

7
  • Can you add more details, that book object should be a FormBuilder, maybe you're shadowing some variable. Commented Sep 20, 2017 at 15:51
  • How can I check that? I'm sort of new to Rails. Commented Sep 20, 2017 at 16:01
  • Does the fields_for work without rendering the partial, just "inline"? Commented Sep 20, 2017 at 16:07
  • Yes. See question update. Commented Sep 20, 2017 at 16:13
  • You're using the same outer variable outside in the fields_for block, try with builder instead form. Commented Sep 20, 2017 at 16:46

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.