#102 Auto-Complete Association

Usually a select menu is used for setting a belongs_to association, but in this episode I will show you how to use a text field with auto completion.
script/plugin install auto_complete

# product.rb
def category_name
  category.name if category
end

def category_name=(name)
  self.category = Category.find_or_create_by_name(name) unless name.blank?
end

# categories_controller.rb
def index
  @categories = Category.find(:all, :conditions => ['name LIKE ?', "%#{params[:search]}%"])
end

<!-- products/_form.html.erb -->
<p>
  <%= f.label :category_name %>
  <%= text_field_with_auto_complete :product, :category_name, { :size => 15 }, { :url => formatted_categories_path(:js), :method => :get, :param_name => 'search' } %>
</p>

<!-- categories/index.js.erb -->
<%= auto_complete_result @categories, :name %>

你可能感兴趣的:(html,F#)