我正在尝试对一个对象子集进行 fields_for 并苦苦挣扎。以下是一些细节:
class Club < ActiveRecord::Base
has_many :shifts
...
<%= form_for club, :url => shift_builders_url do |f| %>
...
<% these_shifts = Shift.where(:club_id => club.id, :date => date) %>
<%= f.fields_for :shifts, these_shifts do |s| %>
<td><%= render "shift_fields", :f => s %></td>
<% end %>
...
因此该代码基本上可以按预期工作,尽管在视图中进行这些调用显然很糟糕。为了清理代码,我添加了以下控制器代码:
...
@shifts_by_club_and_date = sort_shifts_by_club_and_date(@shifts)
...
private
def sort_shifts_by_club_and_date(shifts)
return_hash = Hash.new
shifts.each do |s|
return_hash["#{s.club_id}-#{s.date}"] ? return_hash["#{s.club_id}-#{s.date}"] << s : return_hash["#{s.club_id}-#{s.date}"] = [s]
end
return return_hash
end
然后当我这样做时:
<%= form_for club, :url => shift_builders_url do |f| %>
...
<% these_shifts = @shifts_by_club_and_date["#{club.id}-#{date}"] %>
<%= f.fields_for :shifts, these_shifts do |s| %>
<td><%= render "shift_fields", :f => s %></td>
<% end %>
...
它没有接收该数组,而是执行以下操作:
Shift Load (7.3ms) SELECT `shifts`.* FROM `shifts` WHERE (`shifts`.club_id = 2)
然后为该俱乐部的每个班次对象绘制字段...传入 Arel 对象似乎工作正常,但数组似乎不行。让 fields_for 仅绘制对象子集的最佳方法是什么?
我看过这个类似的问题,但我认为我不能像 has_many :shifts_on_day(date)... 那样进行关联。
编辑添加:我正在使用 MySQL 在 REE 上运行 Rails 3.0.7