我試圖做fields_for對象的子集的掙扎一些通過。這裏還有一些細節: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僅僅繪製一個對象子集的最佳方法是什麼?
我已經看了this similar question,但我不認爲我可以做這樣的has_many協會:shifts_on_day(日期)....
編輯補充: 我運行的Rails 3.0.7在使用MySQL REE
因此,這引起了正確的領域,但它無法正確地更新它們,形式的東西是有點畸形。我想,我可以重寫控制器的代碼來處理高飛表單提交:'參數:{ 「俱樂部」=> { 「移」=> { 「START_TIME(1i)中」=> 「2011」, 「START_TIME(2I)」 => 「5」, 「START_TIME的(3R)」=> 「22」, 「START_TIME(4I)」=> 「19」, 「END_TIME(1i)中」=> 「2011」, 「START_TIME(5I)」=> 「20」, 「END_TIME(2I)」=> 「5」, 「跟隨」=> 「0」, 「END_TIME的(3R)」=> 「22」, 「END_TIME(4I)」=> 「17」,「 _destroy 「=>」」, 「END_TIME(5I)」=> 「20」}, 「ID」=> 「2」}}'而不是 「俱樂部」=>當然工作的 「變換」 ... – alkaloids 2011-05-22 22:57:57