简体   繁体   中英

Getting Values from Database in Ruby on Rails

I have a simple doubt. I've two drop down fields one for states and other for cities. Im loading these two from my database where I have two tables with name states and cities. Also when I select one state cities are changed acordingly as I have written a jquery code too.. This is how I load all states into my select tag

<%= jl.select :state_id , State.all.map{|j| [j[:name], j[:id]]}, {class: 'select2'} %>        

What I want is when I load that page intialy I dont want my cities field to be blank. I want it to be a dropdown list full of cities corresponding to some particular state_id. So how should my select tag for cities should Look. City table contains name,id and state_id.

Add id to your states dropdown

<%= jl.select :state_id , State.all.map{|j| [j[:name], j[:id]]}, {class: 'select2',id:'states_dropdown'} %>  

Then your Cities dropdown should look as the following:

<%= jl.select :city_id , City.where(:state_id=> "specific_id").map{|j| [j[:name], j[:id]]}, {class: 'select2'} %> 

and add this in your coffee script file

$("#states_dropdown").change ->
        $.ajax
            url: '/category/childrens'
            type: 'GET'
            data : 
                state_id: $(this).val()
            success: (data, status, response) ->
                #update cities dropdown
            error: ->
                # Hard error

you should write code on load.

var cities_obj_arr = <%= @cities.to_json %>;

$(document).on('change', "#state_select_box", function(){
  var state_id = $(this).val();
  var str_option = '';
  $.each(cities_obj_arr, function(index, city_obj){
     if(state_id == city_obj['city']['state_id']){
       str_option = str_option + "<option value='"+city_obj['city']['name']+"'">"+city_obj['city']['name']+"</option>"; /*city_obj['city']['name'] city is object name for cities*/
     }
  });
  $(this).html(str_opotion);
});

please have a look on image, it will help more.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM