2

オブジェクトのサブセットの 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を実行しています

4

3 に答える 3

1
<%= form_for club, :url => shift_builders_url do |f| %>
...      
<% these_shifts = club.shifts_for_date(some_date) %>
<%= f.fields_for :shifts, these_shifts do |s| %>
  <td><%= render "shift_fields", :f => s %></td>
<% end %>

モデル

class Club < AR::Base
  has_many :shifts
  ...
  def shifts_for_date(date)
    shifts.where(:date => date)
  end
  ...
end
于 2011-05-22T20:39:18.973 に答える
0

置き換えてみてください:

<%= f.fields_for :shifts, these_shifts do |s| %>
  <td><%= render "shift_fields", :f => s %></td>
<% end %>

と :

<% for shift in these_shifts do %>
 <td><%= f.field_for :shift %></td>
<% end %>
于 2011-05-22T20:19:49.040 に答える