#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 %>
發佈了108 篇原創文章 · 獲贊 0 · 訪問量 2929
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章