如何使用simple_form和嵌套表单通过关联为has_many创建嵌套表单?

时间:2013-03-17 23:16:17

标签: ruby-on-rails nested-forms simple-form has-many-through nested-form-for

我有一个rails应用程序,它有一个专辑和歌曲模型,有很多关系。我正在尝试使用simple_formnested_form宝石为相册添加歌曲。

如果我使用simple_form,则很容易创建关联,但是我无法使用nested_form。看来这应该有效:

<%= 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>

但是我收到了这个错误:RuntimeError in Albums#new Association :songs not found。如果我只使用simple_form,该关联可以正常工作。

正确的语法是什么?或者这些宝石不兼容?如果两个宝石不兼容,那么如何使用nested_form添加和删除相册中的歌曲?

/视图/专辑/ _form https://gist.github.com/leemcalilly/51e7c5c7e6c4788ad000

/模型/专辑 https://gist.github.com/leemcalilly/9a16f43106c788ab6877

/模型/歌曲 https://gist.github.com/leemcalilly/0ccd29f234f6722311a0

/模型/ albumization https://gist.github.com/leemcalilly/c627ad2b178e1e11d637

/控制器/ albums_controller https://gist.github.com/leemcalilly/04edf397b2fb2a3d0d1d

/控制器/ songs_controller https://gist.github.com/leemcalilly/bcbccc9259c39d0b6b7a

1 个答案:

答案 0 :(得分:6)

表单构建器song_form代表Song对象,而不是Album,这就是找不到关联的原因。

fields_for之后的块中,您可以手动创建歌曲的表单。就像@david在评论中提到的那样,您应该使用simple_fields_for代替fields_for to get all simple_form methods available。结果如下:

<%= 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 %>