Skip to content

@abrambailey /gist:2347355
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
models/product.rb
def category_name category.try(:name) end def category_name=(name) self.category = Category.find_or_create_by_name(name) if name.present? end def category_name
category.try(:name)
end
def category_name=(name)
self.category = Category.find_or_create_by_name(name) if name.present?
endapp/assets/javascripts/application.js
//= require jquery-ui
//= require jquery-uiapp
/assets/javascripts/products.js.coffee
jQuery -> $('#product_category_name').autocomplete source: $('#product_category_name').data('autocomplete-source') jQuery ->
$('#product_category_name').autocomplete
source: $('#product_category_name').data('autocomplete-source')
app/assets/stylesheets/application.css.scss
ul.ui-autocomplete { position: absolute; list-style: none; margin: 0; padding: 0; border: solid 1px #999; cursor: default; li { background-color: #FFF; border-top: solid 1px #DDD; margin: 0; padding: 0; a { color: #000; display: block; padding: 3px; } a.ui-state-hover, a.ui-state-active { background-color: #FFFCB2; } } } ul.ui-autocomplete {
position: absolute;
list-style: none;
margin: 0;
padding: 0;
border: solid 1px #999;
cursor: default;
li {
background-color: #FFF;
border-top: solid 1px #DDD;
margin: 0;
padding: 0;
a {
color: #000;
display: block;
padding: 3px;
}
a.ui-state-hover, a.ui-state-active {
background-color: #FFFCB2;
}
}
}
Server Side Solution
products/_form.html.erb
<%= f.text_field :category_name, data: {autocomplete_source: categories_path} %>
rails g controller categories rails g controller categories
config/routes.rb
resources :categories
categories_controller.rb
def index @categories = Category.order(:name).where("name like ?", "%#{params[:term]}%") render json: @categories.map(&:name) end def index
@categories = Category.order(:name).where("name like ?", "%#{params[:term]}%")
render json: @categories.map(&:name)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.