Cities Text Field with Auto Complete in Rails

I've searched a little about some ways to add a second field after States, to set a City based on it. I saw two options first : observe_field (From prototype) and jQuery, both with a select box. The fact is that I don't know JavaScript, and am in a hurry to set this... Well, I thought a text field with auto completion would be better, and maybe easiest to do.

Here we go : I have an model Uf and City, and both is populated with data. City has a "belongs_to Uf". The question is : How can I set something like this? Is there a way to do this with only ruby and rails?

Upvotes: 2

Views: 2380

Answers (1)

Anthony E
Anthony E

Reputation: 11235

To do this you'll want to have an AJAX action that responds to some search string query sent each time the user enters text. This action would respond to the view with data containing the result set of the search.

Here's a very simple example:

City Controller:

def search
    term  = params[:term]
    cities = City.where('name LIKE ? OR code LIKE ?', "%#{term}%", "%#{term}%").order(:name)
    render json: cities.map { |city|
      {
        id:    city.id,
        label: city.inspect,
        value: city.full_name
      }
    }
end

Upon receiving a response, the dropdown would be populated with the results of the search. Selecting a value would set the field and store the matching id for the city in a hidden field for when the form is submitted.

I'd consider exploring the jQuery autocomplete Gem. If you're using Rails, there's a full-stack version here https://github.com/bigtunacan/rails-jquery-autocomplete which should be good to learn from.

Upvotes: 2

Related Questions