奇怪的循环行为 - 这里发生了什么?

时间:2012-04-30 17:01:43

标签: ruby-on-rails ruby-on-rails-3 activerecord

让自己对我认为是双循环并且不知道如何修复它感到困惑。有人可以让我免于疯狂吗?

这在我的节目视图中有效:

<% @releases_tracks_temp.each do |releases_track| %>
  <tr>
    <td><%= releases_track.track.id %> / <%= releases_track.position %></td>
    <td><%= releases_track.track.name %>
        <%= releases_track.track.artists.map { |a| a.name}.join (", ") %></td>
    <td><%= releases_track.track.isrc %></td>
    <td><%#= link_to image_tag("icons/delete.png"), releases_track, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>

我正在尝试使用自定义操作和视图为多个曲目渲染表单:

<%= form_for @release do |f| %>
  <%= f.fields_for :tracks do |builder| %>
     <%= render 'track_fields', :f => builder %>
  <% end %>
  <%= link_to_add_fields "Add track", f, :tracks %>

然后是字段本身:

<% @releases_tracks_temp.each do |releases_track| %>
  <%= f.text_field :name, :class => "text" %>
  <%= f.text_field :artist_tokens, "data-pre" => releases_track.track.artists.map(&:attributes).to_json, :class => "track_artist_tokens" %>
  <%= f.text_field :version, :class => "text" %>
  <%= f.text_field :isrc, :class => "text" %>
  <%= f.select(:asset_tier, options_for_select([['Front', 'Front'], ['Mid', 'Mid'], ['Back', 'Back']]), {}, :class => "tier-select") %>
  <%= f.text_field :preview_start, :class => "text small" %>
  <%= f.check_box :parental_advisory %>
  <%= f.check_box :available_separately, {:checked => true} %>
  <%= f.check_box :_destroy %>
<% end %>

我最终得到它循环但是那个数字有很多曲目,例如5个曲目显示5次!那么25个结果。我想我看到了一个双循环,但我不知道如何解决这个问题,并且仍然可以通过以下方式访问每个音轨的(多个)艺术家:

releases_track.track.artists.map(&:attributes)

有什么想法吗?

哦,@ releases_tracks_temp在我的版本控制器中定义为:

 @releases_tracks_temp = @release.releases_tracks.find(:all, :order => "position") 

根据版本嵌套跟踪曲目。

提前致谢!!!

1 个答案:

答案 0 :(得分:1)

对于每个版本,为每个轨道打印列表。无需循环遍历两次

有一个表单而不是2个

<%= form_for @release do |f| %>
  <%#= f.fields_for :tracks do |builder| %>
    <%= render 'track_fields', :f => f %>
  <%# end %>
<% end %>

编辑 - 尝试这种方式

<%= form_for([@release, @release.tracks.build]) do |f| %>
  <%= f.text_field :name, :class => "text" %>
  <%= f.text_field :artist_tokens, "data-pre" => releases_track.track.artists.map(&:attributes).to_json, :class => "track_artist_tokens" %>
  <%= f.text_field :version, :class => "text" %>
  <%= f.text_field :isrc, :class => "text" %>
  <%= f.select(:asset_tier, options_for_select([['Front', 'Front'], ['Mid', 'Mid'], ['Back', 'Back']]), {}, :class => "tier-select") %>
  <%= f.text_field :preview_start, :class => "text small" %>
  <%= f.check_box :parental_advisory %>
  <%= f.check_box :available_separately, {:checked => true} %>
  <%= f.check_box :_destroy %>

  <%= link_to_add_fields "Add track", f, :tracks %>
<% end %>