配列フォームでtext_field_with_auto_completeってどうやるの?

yotaropg2007-09-06

Railsのソース読んだり検索したりしたけど、やりかたが解らん。
仕方ないので別のヘルパメソッドを追加。基本的にそのままに、ただし配列添字をパラメータ渡ししてコントローラ側で対応。

#ヘルパに追加
  def array_text_field_with_auto_complete(index, object, method, tag_options = {}, completion_options = {})
    object_name = object.to_s.gsub(/\[\]$/, "")
    object_name_with_index = object_name + "_#{index}"
    (completion_options[:skip_style] ? "" : auto_complete_stylesheet) +
    text_field(object, method, tag_options) +
    content_tag("div", "", :id => "#{object_name_with_index}_#{method}_auto_complete", :class => "auto_complete") +
    auto_complete_field("#{object_name_with_index}_#{method}", { :url => { :action => "auto_complete_for_#{object_name}_#{method}", :object_index => index } }.update(completion_options))
  end
#ビューはこんな感じ。
<% @food_properties.each_with_index do |@food_property, index| %>
	<tr>
	  <td nowrap><%= text_field 'food_property[]', 'eated_at', :size => 5, :value => @food_property.eated_at ? @food_property.eated_at.strftime("%H:%M") : nil  %></td>
	  <td nowrap><%= array_text_field_with_auto_complete index, 'food_property[]', 'name', :size => 24, :skip_style => true  %></td>
	</tr>
<% end %>
#でコントローラにこれを追加。
  def auto_complete_for_food_property_name
    search = params[:food_property][params[:object_index]][:name]
    unless search.blank?
      @items = FoodProperty.find :all, :conditions => ["name like ?", "%#{search}%"], :select => "distinct *", :order => "eated_at desc, name asc"
    end
    render :inline => "<%= auto_complete_result @items, 'name' %>"
  end


これで入力が楽になりました。