我目前有三个模型:歌曲有很多 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"}
感谢您提前提供任何帮助