Lee McAlilly
Lee McAlilly

Reputation: 9316

How to create a nested form for a has_many through association using simple_form and nested form?

I have a rails app that has an album and song model with a has many through relationship. I'm trying to add songs to albums using the simple_form and nested_form gems.

If I use simple_form, it's easy to create the association, but I'm having trouble getting it to work with nested_form. It seems that this should work:

<%= f.fields_for :songs do |song_form| %>
  <%= song_form.association :songs %>
  <%= song_form.link_to_remove "Remove this song" %>
<% end %>
<p><%= f.link_to_add "Add a song", :songs %></p>

But I get this error: RuntimeError in Albums#new Association :songs not found. The association works fine if I just use simple_form.

What would the correct syntax be? Or are these gems incompatible? If the two gems are not compatible, then how would you add and remove songs from albums using just nested_form?

/views/albums/_form https://gist.github.com/leemcalilly/51e7c5c7e6c4788ad000

/models/album https://gist.github.com/leemcalilly/9a16f43106c788ab6877

/models/song https://gist.github.com/leemcalilly/0ccd29f234f6722311a0

/models/albumization https://gist.github.com/leemcalilly/c627ad2b178e1e11d637

/controllers/albums_controller https://gist.github.com/leemcalilly/04edf397b2fb2a3d0d1d

/controllers/songs_controller https://gist.github.com/leemcalilly/bcbccc9259c39d0b6b7a

Upvotes: 4

Views: 2917

Answers (1)

siekfried
siekfried

Reputation: 2964

The form builder song_form represents a Song object, not an Album, this is why the association is not found.

In the block following fields_for, you can manually create the form for a song. And like @david mentioned in his comment, you should use simple_fields_for instead of fields_for to get all simple_form methods available. Which results in:

<%= f.simple_fields_for :songs do |song_form| %>
  <%= song_form.input :artwork %>
  <%= song_form.input :track %>
  ...
  <%= song_form.link_to_remove "Remove this song" %>
<% end %>

Upvotes: 6

Related Questions