gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:30:58 24 4
gpt4 key购买 nike

我有一个 rails 应用程序,它有一个专辑和歌曲模型,其中有很多通过关系。我正在尝试使用 simple_form 将歌曲添加到专辑中和 nested_form gem 。

如果我使用 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,该关联就可以正常工作。

正确的语法是什么?还是这些 gem 不相容?如果这两个 gem 不兼容,那么您将如何仅使用nested_form 在专辑中添加和删除歌曲?

/ View /相册/_form
https://gist.github.com/leemcalilly/51e7c5c7e6c4788ad000

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

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

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

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

/controllers/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 %>

关于ruby-on-rails - 如何使用 simple_form 和嵌套表单通过关联为 has_many 创建嵌套表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15467465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com