`
CaiDeHen
  • 浏览: 94287 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

#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 %>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics