RoR嵌套模型不太合适

时间:2015-07-22 22:35:53

标签: ruby-on-rails ruby

我一直试图解决这个问题。在大多数情况下,这一切都有效,但当我尝试添加多首歌曲时,它只保存1(最近的一首)并且不会将多首歌曲保存到专辑模型中。我跟着贝茨(修订版)教程,似乎无法弄明白。任何帮助将不胜感激。

application_helper.rb

module ApplicationHelper
  def link_to_add_fields(name, f, association)
    new_object = f.object
    id = new_object.object_id
    fields = f.fields_for(association, new_object, child_index: id) do |builder|
      render(association.to_s.singularize + "_field", f: builder)
    end
    link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
  end

_form.html.erb

<%= simple_form_for [@band, @album] do |f| %>
  <%= render 'album_field', f: f %>
  <%= link_to_add_fields "Add Album", f, :albums %><br />
  <%= link_to 'Back', band_album_path(current_band, @album) %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

_album_field.html.erb

<fieldset>
  <%= f.label :content, "Album" %><br />
  <%= f.text_field :title %><br />
  <%= f.label :content, "Comment" %><br />
  <%= f.text_area :comment %><br />
  <%= f.fields_for :songs do |builder| %><br />
    <%= render 'song_field', f: builder %>
  <% end %>
  <%= link_to_add_fields "Add Song", f, :songs %><br />
</fieldset>

_song_field.html.erb

<fieldset>
  <%= f.label :content, "Song" %>
  <%= f.text_field :title %>
  <%= f.hidden_field :_destroy %>
  <%= link_to "remove", '#', class: "remove_fields" %>
</fieldset>

1 个答案:

答案 0 :(得分:0)

application_helper.rb 中的

我改变了:

new_object = f.object

new_object = f.object.send(association).klass.new

现在一切都很顺利。