加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何使用simple_form和嵌套表单通过关联为has_

发布时间:2020-12-17 03:04:56 所属栏目:百科 来源:网络整理
导读:我有一个rails应用程序,有一个专辑和歌曲模型,有很多关系.我正在尝试使用 simple_form和 nested_form宝石将歌曲添加到相册中. 如果我使用simple_form,则很容易创建关联,但是我无法使用nested_form.看来这应该有效: %= f.fields_for :songs do |song_form| %
我有一个rails应用程序,有一个专辑和歌曲模型,有很多关系.我正在尝试使用 simple_form和 nested_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 #new关联:未找到歌曲.如果我只使用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

解决方法

表单构建器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 %>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读