Trenton Tyler
Trenton Tyler

Reputation: 1712

Rails undefined method form fields_for

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.

Upvotes: 1

Views: 1090

Answers (1)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

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.

Upvotes: 1

Related Questions