2011-07-28 24 views
14

Tôi có hai hộp thả xuống trong ứng dụng của mình. Dựa trên giá trị được chọn trong hộp kết hợp thứ nhất, các giá trị trong hộp thả xuống thứ 2 phải được điền. Và các giá trị này phải đến từ Cơ sở dữ liệu.Ruby on Rails - hộp thả xuống trên sự kiện thay đổi

Hãy giúp tôi.

Trả lời

9

Bạn có thể lấy cảm hứng từ những gì tôi có trong dự án của tôi. Nó cập nhật trạng thái cho quốc gia được chọn. Nó làm cho sử dụng Carmen một viên ngọc lớn niêm yết quốc gia, khẳng định vv ...

Xem:

<p> 
    <label>Country <span>*</span></label> 
    <%= profile_form.select(:country,Carmen.countries, {:include_blank => 'Select a Country'}, :id => "profile_country") %> 
</p> 
<p> 
    <label>State <span>*</span></label> 
    <%= profile_form.select(:state, "" , {:include_blank => 'Select a Country first'}, :id => "profile_state") %> 
</p> 

Jquery mã:

$('#profile_country').change(function() { 
    if ($(this).val() == '') 
    { 
    $('#profile_state').html($('<option>No state provided for your country</option>')); 
    } 
    else { 
    $.ajax({ 
    type: "GET", 
    url: "/remote/get_states/" + encodeURIComponent($(this).attr('value')), 
    success: function(data){ 
     if (data.content == 'None') //handle the case where no state related to country selected 
     { 
     $('#profile_state').empty(); 
     $('#profile_state').append($('<option>No state provided for your country</option>')); 
     } 
     else 
     { 
     $('#profile_state').empty(); 
     $('#profile_state').append($('<option>Select your State</option>')); 
     jQuery.each(data,function(i, v) { 
      $('#profile_state').append($('<option value="'+ data[i][1] +'">'+data[i][0] +'</option>')); 
     }); 
     } 
    } 
    }); 
} 
}); 

Bộ điều khiển:

def states 
    begin 
    render :json => Carmen::states(CGI::unescape(params[:country])) 
    rescue 
    render :json => {"content" => "None"}.to_json 
    end 
end 
16

đây một cách tiếp cận sạch sẽ bằng cách sử dụng jquery-ujs (https://github.com/rails/jquery-ujs)

Theo quan điểm của bạn:

<%= 
    select_tag 
     :first_select, # name of selectbox 
     options_from_collection_for_select(@myrecords, "id", "name"), # your options for this select box 
     :'data-remote' => 'true', # important for UJS 
     :'data-url' => url_for(:controller => 'MyController', :action => 'getdata'), # we get the data from here! 
     :'data-type' => 'json' # tell jQuery to parse the response as JSON! 
%> 


<%= 
    select_tag 
     :second_select, # name of selectbox 
     "<option>Please select something from first select!</option>" 
%> 

điều khiển của bạn:

class MyController < ApplicationController 


    def getdata 
    # this contains what has been selected in the first select box 
    @data_from_select1 = params[:first_select] 

    # we get the data for selectbox 2 
    @data_for_select2 = MyModel.where(:some_id => @data_from_select1).all 

    # render an array in JSON containing arrays like: 
    # [[:id1, :name1], [:id2, :name2]] 
    render :json => @data_for_select2.map{|c| [c.id, c.name]} 
    end 
end 

Trong application.js của bạn:

$(document).ready(function() { 

    // #first_select is the id of our first select box, if the ajax request has been successful, 
    // an ajax:success event is triggered. 

    $('#first_select').live('ajax:success', function(evt, data, status, xhr) { 
    // get second selectbox by its id 
    var selectbox2 = $('#second_select'); 

    // empty it 
    selectbox2.empty(); 

    // we got a JSON array in data, iterate through it 

    $.each(data, function(index, value) { 
     // append an option 
     var opt = $('<option/>'); 

     // value is an array: [:id, :name] 
     opt.attr('value', value[0]); 
     // set text 
     opt.text(value[1]); 
     // append to select 
     opt.appendTo(selectbox2); 
    }); 
    }); 

}); 
+1

Các tuyến đường trông như thế nào đối với 'getdata'? – bcackerman

+0

Tôi hy vọng điều này có thể helpf một người nào đó, đây là cách getdata route trông giống như "get 'getdata' => 'controller # getdata" – JAML

4

Đây là cách tôi đã làm nó. Hoạt động trong Rails 3.2

Xem:

<%= select_tag :major_category_select_id, options_from_collection_for_select(@majorcategories, 'id', 'name'), :'data-remote' => 'true', :'data-url' => url_for(:controller => 'listings', :action => 'submit_major_category', format: 'js') %> 

điều khiển phương pháp:

def submit_major_category 
    @major_category = MajorCategory.find(params[:major_category_select_id]) 
    @minor_categories = @major_category.minor_categories 

    respond_to do |format| 
     # format.html { render partial: 'minor_categories_select' } 
     format.js 
    end 
    end 

Tuyến đường:

get "listings/submit_major_category" 

Sau đó tạo một file submit_major_category.js.erb đó được đáp lại.

+0

Excelent là cách tốt nhất để làm điều này như sử dụng nguyên mẫu. +1 –

+0

Có thể sử dụng trong thanh ray 5 – praveenkumar

Các vấn đề liên quan