Skip to content

Instantly share code, notes, and snippets.

@elricstorm
Last active August 29, 2015 14:03
Show Gist options
  • Save elricstorm/cb68284102e2e133e5d6 to your computer and use it in GitHub Desktop.
Save elricstorm/cb68284102e2e133e5d6 to your computer and use it in GitHub Desktop.
class AjaxController < ApplicationController
skip_authorization_check
def ncaa_teams
if params[:term]
teams = NcaaTeam.where('name LIKE ?', "%#{params[:term]}%").order("name ASC")
else
teams = NcaaTeam.all
end
list = teams.map {|t| Hash[ id: t.id, label: t.name, name: t.name]}
render json: list
end
def nfl_teams
if params[:term]
teams = NflTeam.where('name LIKE ?', "%#{params[:term]}%").order("name ASC")
else
teams = NflTeam.all
end
list = teams.map {|t| Hash[ id: t.id, label: t.name, name: t.name]}
render json: list
end
end
*= require jquery.ui.autocomplete
*/
//= require jquery
//= require jquery.ui.autocomplete
//= require jquery_ujs
//= require responsive-tables
//= require foundation
//= require jquery.purr
//= require best_in_place
//= require sticky_footer
var load_search;
load_search = (function() {
$('#ncaa_team_name').autocomplete({source: "/ajax/ncaa_teams"});
$('#nfl_team_name').autocomplete({source: "/ajax/nfl_teams"});
});
$(document).ready(load_search);
$(document).on('page:load', load_search);
<div class="centered">
<%= form_tag nfl_teams_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search], id: "nfl_team_name", placeholder: 'Find a Team' %>
<%= submit_tag "Search", :name => nil, class: 'round button tiny' %>
</p>
<% end %>
</div>
<!--
Note that you can use any :search or params[:search] parameter that leads to your own model's search method.
Regardless of what you place in here, params[:term] will be sent to the ajax controller via a hidden request.
-->
gem 'jquery-ui-rails'
# one of my models
def ncaa_team_name=(name)
team = NcaaTeam.find_by_name(name)
if team
self.team_id = team.id
else
errors[:team_name] << "Invalid name entered"
end
end
def ncaa_team_name
NcaaTeam.find(team_id).name if team_id
end
# another one of my models
def nfl_team_name=(name)
team = NflTeam.find_by_name(name)
if team
self.team_id = team.id
else
errors[:team_name] << "Invalid name entered"
end
end
def nfl_team_name
NflTeam.find(team_id).name if team_id
end
match '/ajax/ncaa_teams' => "ajax#ncaa_teams", via: :get
match '/ajax/nfl_teams' => "ajax#nfl_teams", via: :get
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment