Skip to content

Instantly share code, notes, and snippets.

@SeriouslyAwesome
Created November 14, 2014 02:36
Show Gist options
  • Save SeriouslyAwesome/dfcb1b5461b51ba4e16a to your computer and use it in GitHub Desktop.
Save SeriouslyAwesome/dfcb1b5461b51ba4e16a to your computer and use it in GitHub Desktop.
Auto-complete tagging with Rails, PostgreSQL Arrays and Chosen: A Complete Example
<%= f.label :name, 'Your Name' %>
<%= f.input :name, placeholder: 'John/Jane Doe' %>
<%= f.label :states_visited, 'States You\'ve Been To' %>
<%= f.select :states_visited, MURICA, {}, { multiple: true, class: 'taggable' } %>
*= require chosen
//= require chosen-jquery
class ApplicationController < ActionController::Base
before_action :clean_select_multiple_params, only: [:create, :update]
# existing stuff...
private
# Used to strip blank first values from array-type params.
def clean_select_multiple_params hash = params
hash.each do |key, value|
case value
when Array then value.reject!(&:blank?)
when Hash then clean_select_multiple_params(value)
end
end
end
end
rails g migration add_states_visited_to_people
jQuery ->
$('.taggable').chosen()
def person_params
params.require(:person).permit(:name, { states_visited: [] })
end
<h2>States I've Been To</h2>
<% if @person.states_visited.any? %>
<ul>
<% @person.states_visited.each do |state| %>
<li><%= state %></li>
<% end %>
</ul>
<% end %>
MURICA = ["Alabama", "Alaska", ..., "Wyoming"]
class AddStatesVisitedToPeople < ActiveRecord::Migration
def change
add_column :people, :states_visited, :text, array: true, :default => []
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment