[英]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. 我有一个Rails应用,其中有专辑和歌曲模型,并且有很多直通关系。 I'm trying to add songs to albums using the simple_form and nested_form gems.
我正在尝试使用simple_form和nested_form宝石将歌曲添加到专辑。
If I use simple_form, it's easy to create the association, but I'm having trouble getting it to work with nested_form. 如果使用simple_form,创建关联很容易,但是我很难使它与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
. 但是我收到以下错误消息:
RuntimeError in Albums#new Association :songs not found
。 The association works fine if I just use simple_form. 如果我只使用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?
如果这两个宝石不兼容,那么如何仅使用nested_form从专辑中添加和删除歌曲?
/views/albums/_form https://gist.github.com/leemcalilly/51e7c5c7e6c4788ad000 / views / albums / _form https://gist.github.com/leemcalilly/51e7c5c7e6c4788ad000
/models/album https://gist.github.com/leemcalilly/9a16f43106c788ab6877 / models / album https://gist.github.com/leemcalilly/9a16f43106c788ab6877
/models/song https://gist.github.com/leemcalilly/0ccd29f234f6722311a0 / models / song https://gist.github.com/leemcalilly/0ccd29f234f6722311a0
/models/albumization https://gist.github.com/leemcalilly/c627ad2b178e1e11d637 / models /相册https://gist.github.com/leemcalilly/c627ad2b178e1e11d637
/controllers/albums_controller https://gist.github.com/leemcalilly/04edf397b2fb2a3d0d1d / controllers / albums_controller https://gist.github.com/leemcalilly/04edf397b2fb2a3d0d1d
/controllers/songs_controller https://gist.github.com/leemcalilly/bcbccc9259c39d0b6b7a / controllers / songs_controller https://gist.github.com/leemcalilly/bcbccc9259c39d0b6b7a
The form builder song_form
represents a Song
object, not an Album
, this is why the association is not found. 表单生成器
song_form
表示Song
对象,而不是Album
,这就是为什么找不到关联的原因。
In the block following fields_for
, you can manually create the form for a song. 在
fields_for
的块中,您可以手动创建歌曲的形式。 And like @david mentioned in his comment, you should use simple_fields_for
instead of fields_for
to get all simple_form methods available . 就像他评论中提到的@david一样,您应该使用
simple_fields_for
而不是fields_for
来获取所有可用的simple_form方法 。 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 %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.