E
E
exvion2014-10-06 21:42:35
Ruby on Rails
exvion, 2014-10-06 21:42:35

How to select the desired value from the list?

We have two models User and City. In the form for creating a new User, you must fill in the City field by selecting from the drop-down list loaded from the City model. The list of cities is large, about 10,000 and will continue to grow. Putting all 10,000 option elements in a select is bad practice.
What is the best way to solve this problem? Maybe there is a ready-made solution or gem?
The City model is taken as an example.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
exvion, 2014-10-23
@exvion

I solved this task with select2+ajax, thanks for pointing the direction.
rails g scaffold City text:string
rails g scaffold User name:string
bundle install

gem 'rails', '4.1.5'
    gem 'select2-rails'
    gem 'mysql2'

var ready;
ready = function() {
  $('#ajax-example').select2({
    minimumInputLength : 0,
    ajax: {
      url: "/cities.json",
      dataType: "json",
      quietMillis: 100,
      data: function(term) { return { q: term }},
      results: function(data) { 
        return { 
          results: $.map( data, function(city, i) { 
            return { id: city.id, text: city.text } 
          } ) 
        } 
      }
    },
    initSelection: function(element, callback) {
      var id=$(element).val();
      if (id!=="") {
        $.ajax("/cities/"+id+".json").done(function(data) {
          data ={ id: data.id, text: data.text } 
          callback(data);
        })
      }
    }       
  });
};
$(document).ready(ready);  //для работы с turbolinks
$(document).on('page:load', ready);

class CitiesController < ApplicationController
      def index
        @cities = City.order('text').finder(params[:q])
        respond_with @cities
      end
    end

<div class="field">
      <%= f.label :city %><br>
      <%= f.hidden_field :city_id, :value =>@user.city_id, id: 'ajax-example', data: { source: cities_path } %>    
  </div>

_
_ _, 2014-10-06
@AMar4enko

select-2, you need to fumble in JS

C
caution, 2014-10-06
@caution

I think that you need something like this:
loopj.com/jquery-tokeninput
the only thing left is to upload your cities to JSON. Only not in the field but in the select

G
gsmetal, 2014-10-16
@gsmetal

Select2 + ajax is the best option in this case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question