使用上一个下拉列表的结果填充下拉列表

时间:2015-04-19 01:42:03

标签: javascript jquery ruby ruby-on-rails-4 web

我有一个包含Schools和Majors的Rails数据库。一旦用户选择了他的学校,我想填写专业的下拉,只有相应学校的专业。目前我有两个工作下降,但你可以看到他们只选择所有值。我是否需要Json / Ajax / JavaScript,如果是这样,我该如何实现呢?

<div class="field">
  <%= f.label :school_id %><br>
  <%= f.collection_select :school_id, School.order(:name),:id,:name, include_blank: false %>
</div>
<div class="field">
  <%= f.label :major_id %><br>
  <%= f.collection_select :major_id, Major.order(:name),:id,:name, include_blank: false %>
</div>

1 个答案:

答案 0 :(得分:5)

修改

当前解决方案是在每个下拉列表选择上使用异步请求。假设你有一个小的总体选择(让我们说&lt; 5k),在页面加载时只有1个异步操作可能会更好,然后在用户做出选择时使用JS来填充下拉列表。这样可以节省大量的网络呼叫,并提供更好的用户体验。

原始

好吧,经过多次搜索,我已经达成了一个正在运行的AJAX请求(我将在这里发帖给后人)。

在我的数据库中创建新课程时,学校和主要外键必须为非空。以下是下拉列表

<!-- app/views/courses/_form.html.erb -->
<div class="field">
  <%= f.label :school_id %><br>
  <%= f.collection_select :school_id, School.order(:name),:id,:name, {include_blank: false},{:id=>'school_id_select'} %>
</div>
<div class="field">
  <%= f.label :major_id %><br>
  <%= f.collection_select :major_id, [],:id,:name, {include_blank: false},{:id=>'major_id_select'} %>
</div>

现在HTML已经启动,我们需要一些JavaScript(和jQuery)来处理AJAX请求

//app/assests/javascripts/courses.js (note this was generated as a .coffee file, which I changed to .js as I don't know CoffeeScript
console.log('loaded courses.js')//check that the file is loaded

$(document).on('change','#school_id_select', function () {//change majors when user changes school
   load_majors_from_school_dropdown();
});

$(document).ready(load_majors_from_school_dropdown);//populate majors when page loads with first school

function load_majors_from_school_dropdown(){
    var request = "/majors/find_majors_given_school_id?school_id=" //access controller of interest
        + $('#school_id_select').val();

    var aj = $.ajax({
        url: request,
        type: 'get',
        data: $(this).serialize()
    }).done(function (data) {
         change_majors(data);//modify the majors' dropdown
    }).fail(function (data) {
         console.log('AJAX request has FAILED');
    });
};

//modify the majors' dropdown
function change_majors(data) { 
    $("#major_id_select").empty();//remove all previous majors
    for(i = 0;i<data.length;i++){ 
        $("#major_id_select").append(//add in an option for each major
            $("<option></option>").attr("value", data[i].id).text(data[i].name)
        );
    }
};

请注意&#39;请求&#39;变量。这表明控制器&amp;将处理请求的操作。现在我们必须成功。我的Major控制器已经存在,所以我们只需要添加动作。首先添加操作的路由,使Rails服务器知道该操作。

#config/routes.rb
Rails.application.routes.draw do
  #...
  get 'majors/find_majors_given_school_id'
  #...
end

现在在Major控制器中创建动作

#app/controllers/majors_controller.rb
#custom action for AJAX/JSON calls. Note this can be done multiple ways
def find_majors_given_school_id
   school_id = params[:school_id]#utilizes the url to extract school_id ".../find_majors_given_school_id?school_id=123123"
   puts "THIS IS MY SCHOOL ID :: #{school_id}"#view this in teminal

   majors = Major.search_for_school_id(school_id).as_json#query the model for the data and convert it to a hash using as_json
   puts "THESE ARE MY MAJORS IN A HASH :: #{majors}"
   respond_to do |format|
        format.json { 
            render json: majors
        } 
   end
end

最后,我们必须创建查询以在模型中提取此信息。

#app/models/major.rb
class Major < ActiveRecord::Base
    has_many :courses, dependent: :destroy
    belongs_to :school, :foreign_key => "school_id"

    def self.search_for_school_id(id)
        where("school_id = ?",id)        
    end
    #...
end

我认为这就是一切。肯定有其他方法可以实现这一点,但这个方法对我有用。祝你好运!