我有点坚持创建一个有很多关系的表单。目前我的模型是歌曲可以有多个Setlists,反之亦然,通过Allocations。
我目前正在编辑一个编辑页面,用户可以在其中添加歌曲到设置列表。该视图目前看起来像这样:
<h1>Edit a Setlist</h1>
<div class="row">
<div class="span8">
<%=form_for(@setlist) do|f|%>
<%=f.label :date, "Set a date" %>
<span><%=f.date_select :date%><span>
<div>
<div id="library">
<%= render 'library' %>
</div>
<%= render 'songs_in_set' %>
</div>
<%=f.submit "Save", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
上面提到的库部分:
<table class= "table table-striped table-bordered">
<thead>
<th>Title</th>
<th>Artist</th>
<th>Add to Set</th>
</thead>
<tbody>
<% @songs.each do |song| %>
<tr>
<td><%= song.title %></td>
<td><%= song.artist %></td>
<td><%= link_to "ADD", '#' %></td>
</tr>
<% end %>
</tbody>
</table>
我想将库中的链接部分转换为用于创建新分配的表单,从而将歌曲添加到集合列表中。
我的控制器的相关位: setlist控制器:
def edit
@songs = Song.all(order: 'title')
@setlist = Setlist.find(params[:id])
@allocations = @setlist.allocations
end
def update
@setlist = Setlist.find(params[:id])
if @setlist.update_attributes(params[:setlist])
flash[:success] = "SAVED!"
redirect_to setlist_path(@setlist)
else
render 'edit'
end
end
和分配控制器:
def new @allocation = Allocation.new 端
def create
@allocation = Allocation.new(params[:allocation])
if @allocation.save
flash[:success] = "Songs added"
redirect_to edit_setlist_path(@allocation.setlist_id)
else
flash[:fail] = "Error"
redirect_to edit_setlist_path(@allocation.setlist_id)
end
端
我知道我必须按照setlist.allocations.build的方式做一些事情,但是我无法获得正确的参数(获取每个单独的歌曲ID和setlist id)。我已经尝试在songs.each do循环中添加一个帮助形式,但这似乎不起作用。我有点失落所以任何正确方向的指针都会受到赞赏。提前致谢
答案 0 :(得分:0)
尝试将此添加到Setlist
:
accepts_nested_attributes_for :allocations, :dependent => :destroy
然后,您可以在setlist表单中嵌套关联字段集。在图书馆部分:
<td>
<%= f.fields_for :allocations do |ff| %>
<%= f.hidden_field :song_id, song.id %>
...
<% end %>
</td>
如果您想为已经存在的歌曲创建分配,这应该有效,但是当您也以相同的形式创建歌曲时,您可能需要一些不同的场景。我不久前遇到过这样的问题,并且无法找到一个干净的解决方案,但请告诉我,我也可以分享一下......