Question

I am trying to get my head around how you are supposed to access objects using the Rails Form Builder (or in this case, simple_form).

I pass in the object as described in http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for like so:

- @document.sections.each do |section|
  = f.simple_fields_for :sections, section do |section_form|
    = render 'section_fields', :f => section_form

However when I call f.object inside the partial, I get a 'new' Section object containing nil id etc, breaking my link_to path.

Even passing in variables the 'standard' way seems to be broken, such as:

- @document.sections.each do |section|
  = f.simple_fields_for :sections, section do |section_form|
    = render 'section_fields', :f => section_form, :foo => section

having foo undefined inside the partial.

How am I supposed to access the intended object that the form is being built for using a fields_for has_many association?

Était-ce utile?

La solution 2

It turns out that the Cocoon method 'link_to_add_association' was generating a new object which was breaking the link_to that included f.object, as the object obviously didn't exist at that point.

Simply adding 'unless f.object.new_record?' ignores the new (hidden) record that Cocoon generates.

Autres conseils

I think you need build associated object and change you code like this:

- @document.sections.build if @document.sections.empty?
  = f.simple_fields_for :sections, @document.sections do |section_form|
   = render 'section_fields', :f => section_form
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top