4

我有一个Rails应用程序,拥有一个拥有很多关系的专辑和歌曲模型。我正在尝试使用simple_formnested_form宝石将歌曲添加到相册中。如何使用simple_form和嵌套窗体通过关联为has_many创建嵌套窗体?

如果我使用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

你可以发布你的相册控制器吗?它看起来就是错误来自的地方。 – 2013-03-17 23:45:55

+0

编辑它以包含我的控制器。 – 2013-03-18 14:38:52

+0

在您的'albuns_controller.rb'的'new'动作中添加一个'@ album.songs.build'。 – MurifoX 2013-03-18 14:42:43

回答

6

表单生成器song_form表示Song对象,而不是一个Album,这就是为什么没有找到相关性。

fields_for后面的块中,您可以手动创建歌曲的表单。就像他在评论中提到的@david一样,您应该使用simple_fields_for而不是fields_forto 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 %> 
+0

我试图创建专辑和歌曲之间的关联,而不是通过专辑表单创建歌曲。我正在用不同的歌曲形式创作歌曲。只要将歌曲的字段作为输入,不会创建与预先存在的歌曲的关联。我试过这个https://gist.github.com/leemcalilly/699cbac054849b407353,但那也给我一个错误。是否有一些语法来创建我缺少的关联?这可能与simple_nested_form_for?如果没有,那么正常的rails has_many的语法是什么:通过这种形式的关联? – 2013-03-26 19:57:20