A
A
Anton Misyagin2015-03-18 21:12:56
Ruby on Rails
Anton Misyagin, 2015-03-18 21:12:56

How to create and populate linked dropdown lists in Rails?

Hello. I have a question, the answer to which I do not yet have, but I hope with your help I will get to the truth. Application on RubyOnRails 4. The simple_form gem is used. There are three models
shop, city, district (shops, cities and districts respectively)
shop:
belongs_to :district
district:
belongs_to :city
city
mas_many :districts
There is a link to the district id in the shops table. In the table of districts, a link to the city id. From the store I can find the area shop.district or the city: shop.district.city
The task with the least effort is to create a form for editing the store, which will display 2 drop-down lists: City, District
I can create and fill lists. The catch is that the list of possible districts depends on the selected city. How to get by with little blood? I'm used to the fact that there is almost no need to create bicycles on Rails.
I came across a similar question . Not a bad decision in general. Here both districts and cities appear in one list. The regions are grouped by cities. It didn't work for me, the list is too long. It needs to be divided into two lists.
Bicycles suggest Ajax, or load all drop-down lists of districts at once, for each city and hide / display the required one depending on the selected city. But it's not pretty and verbose. Is there already a solution?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
N. Bekseitov, 2015-03-19
@sunnmas

Railscasts PRO #088 dynamic select menus

A
Anton Misyagin, 2015-03-19
@sunnmas

so far it turned out by the crutch method:

<% cities = City.all.map{|city| [city.name, city.id]}%>
<%= select_tag(:city_id, options_for_select(cities)) %>
<% for city in cities %>
<%= select_tag("district_id_"+city[1].to_s, 
    options_for_select(District.where(:city_id => city[1]).map{|d| [d.name, d.id]})) %>
<% end %>

This created a list of cities and a bunch of lists of districts
. Next, we break it down in the browser:
<script>
  $("[name ^= district_id]").hide();
  $("[name = district_id_1]").show();
  $("[name = city_id]").change(function(){
    cur_district = $("[name = 'adv[district_id]']");
    cur_district.attr("name",cur_district.attr("id"));
    $("[name ^= district_id]").hide();
    $("[name = district_id_"+$(this).val()+"]").
        attr("name","adv[district_id]").show();
  });
</script>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question