0

我目前有三个模型:歌曲有很多 Setlists,反之亦然,通过分配模型。

我正在尝试使用嵌套表单将现有歌曲添加到设置列表。

我当前对嵌套表单的看法:

<div>
  <%=form_for @allocation do|builder|%>
    <%=builder.label :song_id, "Pick a song" %>

     <%= builder.hidden_field :setlist_id, value: @setlist.id %>

     <%= builder.select(:song_id, options_for_select(@selections), {}, {multiple: true, size: 7}) %>

    <%=builder.submit "Add Song", class: "btn btn-large btn-primary" %>
  <% end %>
</div>

和我用于编辑设置列表的控制器:

  def edit
    @songs = Song.all(order: 'title')
    @setlist = Setlist.find(params[:id])
    @allocations = @setlist.allocations
    @allocation = Allocation.new
    @selections = Song.all.collect {|s| [ [s.title, s.artist].join(" by "), s.id ]   }
  end

  def update

    @setlist = Setlist.find(params[:id])
    @selections = Song.all.collect {|s| [ [s.title, s.artist].join(" by "), s.id] }
    @allocations = @setlist.allocations
    @allocation = Allocation.new

    params[:allocation][:song_id].reject! { |c| c.empty? }

    if @setlist.update_attributes(params[:setlist])
      if @allocation.save
        flash[:success] = "SETLIST SAVED!"
        redirect_to setlist_path(@setlist)
      else
        flash[:fail] = "Setlist not saved"
        render 'edit'
      end
    else
      flash[:fail] = "FAIL!"
      render 'edit'
    end
  end

每当我提交表单以将歌曲添加到设置列表时,我都会收到一条错误消息:

Validation failed: Setlist can't be blank, Song can't be blank

所有参数似乎都正确传递,所以我很难过。这是返回的参数:

   {"utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"ThIXkLeizRYtZW77ifHgmQ8+UmsGnDhdZ93RMIpppNg=",
 "setlist"=>{"date(1i)"=>"2012",
 "date(2i)"=>"7",
 "date(3i)"=>"11",
 "morning"=>"false"},
 "allocation"=>{"setlist_id"=>"1",
 "song_id"=>["5"]},
 "commit"=>"Add Song",
 "id"=>"1"}

感谢您提前提供任何帮助

4

1 回答 1

1

您允许在该:song_id字段中进行多项选择,我想其中一个选项有一个空白值。必须选择该选项和另一个选项,从而导致["", 13]响应。

params[:allocation][:song_id].reject! { |c| c.empty? }

这将清除该参数中的空白条目。这应该放在update该行之前的任何方法中

if @setlist.update_attributes(params[:setlist])

至于验证错误,我认为它来自表单,Allocation因为这就是表单的用途。

@allocation = Allocation.new

if @allocation.save!

不知道所有属性在此处都有需要值的属性,例如:set_list_id:song_id。您试图在Allocation不先设置任何属性的情况下将其持久化到数据库中。这可能是您遇到的验证问题的来源。

编辑:

rails 中的嵌套表单是与父表单的对象关联的对象的一组表单字段。注意这个表单是如何fields_for调用person_form对象的。这将导致嵌套参数,如param[:person][:children][:name].

<% form_for @person do |person_form| %>

  <%= person_form.label :name %>
  <%= person_form.text_field :name %>

  <% person_form.fields_for :children do |child_form| %>
    <%= child_form.label :name %>
    <%= child_form.text_field :name %>
  <% end %>

  <%= submit_tag %>

在这个update方法中,你可以有一些简单的东西

person = Person.find(params[:id]).update_attributes(params[:person])

on Person 可以为您管理其关联update_attributes的创建、更新和保存childrenaccepts_nested_attributes_for

认为这就是您所追求的,因此您可能需要update相应地重新考虑您的观点和方法。对于绝对的 Rails 初学者来说,这是相对棘手的事情;继续返回文档(写得很好)并在这里寻求帮助。

于 2012-07-12T13:59:19.373 回答