Question

Has anyone worked with the nested_form gem and used a has_many through relationship rather than just has_many? (I'm still new to Rails)

I am working on an app, and in many other places we have used the nested_form gem successfully for dynamically adding and removing fields on a form in the view, but for some reason on this new part of the application where we are using has_many through, the gem is not doing its job anymore.

To better explain, the view is showing the links for "Add" and "Remove" but the javascript is not adding/removing the fields... it's rendering a dead link.

Other sections of the application are working perfectly fine still, and the code coming in from the javascript for nested_form is the same between the two pages. The approach to creating the forms is the same as well... so the only difference I can see is that the other models are using simple has_many relationships while I am dealing with has_many through here.

Not exactly sure what I should post for this issue since I'm not hitting an error from which I could post the trace.

Here is code from the view's form partial:

    = f.fields_for :purchase_request_line_items do |f|
    = render :partial => 'purchase_requests/purchase_request_line_item_fields', :locals => {:f => f}
    %br
    = f.link_to_remove "Remove this item"
  %br
  = f.link_to_add "+ add item(s)", :purchase_request_line_items, :class => 'add_form_section_button'

Here is code from the partial in the above code:

.field
  = f.select(:inventory_item_id, options_for_select(InventoryItem.all.map{ |i| [i.name, i.id] }))

.field
  = f.label :quantity
  = f.text_field :quantity

Of course, I have this in the app as well:

javascript_include_tag :defaults, "nested_form"

I have the javascript_include_tag at the top of the form partial, which is how we placed it in the other (working) sections of the app as well.

Any help would be greatly appreciated. I have never worked with this gem before until yesterday afternoon, so I'm a bit at a loss on this one. I've tried a number of workarounds to no avail at this time.

I'm also still very new to Rails... so apologies if this is something simple.

Also, if more info is needed I would be glad to provide additional details.

Thank you.

Was it helpful?

Solution

So it turns out that if you use Ryan's docs to the letter, it doesn't quite work with the setup we're running. We're running Rails 3.0.9 and Ruby 1.9.3p448.

The docs instruct you to use "javascript_include_tag :defaults, 'nested_form'

I tried out removing ":defaults" and everything now works as it should.

Might be a difference just when using an older version of Rails, but whatever the case... it works now.

Hopefully this helps someone else if they run into the same thing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top