Reputation: 13
I am trying to implement an auto complete feature similar to facebook city selector where one enters the city name and the autocomplete appears in the form "city, state, country". I have dbs of cities states and countries I followed the railscast auto complete video. My code is as follows
Cities controller
def index
@cities = City.order(:name).where("lower(name) like ?", "%#{params[:term].downcase}%")
render json: @cities.map(&:name)
end
User.js.coffee
jQuery ->
$('#user_city_name').autocomplete
source: $('#user_city_name').data('autocomplete-source')
users/new/html.erb
<div class="field">
<%= f.label :city_name %><br />
<%= f.text_field :city_name, data: {autocomplete_source: cities_path} %>
</div>
the city is all that needs to be auto selected but I would like when the user is selecting that they see the auto select option as city, state, country because there are a lot of cities with the same name in different states. can anyone point me in the right direction plz and thank you
Upvotes: 0
Views: 430
Reputation: 13
I figured out how to do it. Changed the cities controller index to
def index
if params[:term]
@cities = City.order(:name).where("lower(name) like ?", "%#{params[:term].downcase}%").includes(:state)
cities_list = @cities.map {|city| Hash[id: city.id, label: "#{city.name}, #{city.state.name}, #{city.state.country.name}", value: city.name]}
render json: cities_list
else
@cities = City.all
end
end
Upvotes: 1