簡體   English   中英

如何通過使用simple_form和嵌套表單的關聯為has_many創建嵌套表單?

[英]How to create a nested form for a has_many through association using simple_form and nested form?

我有一個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從專輯中添加和刪除歌曲?

/ views / albums / _form https://gist.github.com/leemcalilly/51e7c5c7e6c4788ad000

/ models / album https://gist.github.com/leemcalilly/9a16f43106c788ab6877

/ models / song https://gist.github.com/leemcalilly/0ccd29f234f6722311a0

/ models /相冊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 來獲取所有可用的simple_form方法 結果是:

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM