public
Last active

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.