Error using nested_form gem with empty association

In my rails application, I have two models: ClientPage and ContentSection , where ClientPage has_many :content_sections . I use pearl nested_form for both models for editing with the same form. This works fine as long as ClientPage has at least one ContentSection , but if there is no associated ClientSections , the nested_form link_to_add method throws the following NoMethodError :

 undefined method `values_at' for nil:NilClass 

The form is structured as follows:

 <%= nested_form_for page, form_options do |f| %> # ClientPage fields # ClientSections <%= f.link_to_add "Add new section", :content_sections %> <% end %> 

As long as there is at least one ClientSection associated with the page, this works fine. As soon as this does not happen, the error will be reset. Removing link_to_add also stops the error. (Actually the second nested model is under ContentSection , and the same problem occurs if there are no related models.)

Not sure if I'm a pretty obvious thing that I missed, but any pointers or suggestions would be appreciated.

+4
source share
1 answer

Finally, it succeeded - the error occurred due to the fact that I used this stone in a slightly non-standard way. Within a form, instead of providing all sections of content in a standard way:

 <%= f.fields_for :content_sections do |section_form| %> # section fields <% end %> 

I put it inside the loop, since I need the index of each element (which is not stored in the model itself):

 <% page.content_sections.each_with_index do |section, index| %> <%= f.fields_for :content_sections, section do |section_form| %> # section fields <% end %> <% end %> 

The problem with this is that the fields_for method fields_for not called if the association is empty, and therefore such a stone cannot build a project for an object (which is used to add an additional element when link_to_add ).

The solution was to make sure that fields_for received the call, even if the association is empty:

 <% if page.content_sections.empty? %> <%= f.fields_for :content_sections do |section_form| %> # section fields <% end %> <% end %> 
+6
source

Source: https://habr.com/ru/post/1491063/


All Articles