带有ajax动作的Rails select_tag(Rails 3和jQuery)

我有以下选择列表。

 

当用户从上面的列表中选择一个选项时,下面的列表应该根据上面的选择用数据库中的值填充。

  

我想我应该使用onchange事件,但我不知道如何使用它。 请有人帮帮我。 谢谢!

使用Javascript

 function update_versions_div(project_id) { jQuery.ajax({ url: "/update_versions", type: "GET", data: {"project_id" : project_id}, dataType: "html" success: function(data) { jQuery("#versionsDiv").html(data); } }); } 

调节器

 def edit @projects = Project.all @versions = Version.all end def update_versions @versions = Version.where(project_id => params[:project_id]).all render :partial => "versions", :object => @versions end 

视图

 <%= select_tag "project_id", options_from_collection_for_select(@projects, "id", "title"), :prompt => "Select a project", :onchange => "update_versions_div(this.value)" %> 
<%= render :partial => 'versions', :object => @versions %>

部分 :_version.html.erb

 <%= select_tag "version_id", options_from_collection_for_select(versions, "id", "title"), :prompt => "Select a version" %> 

还要在/update_versions中为/update_versions添加路由

 match "/update_versions" => "#update_versions" 

在这里,您应该将替换为名称。

我还没有测试过代码,所以可能会有错误。

更新

PullMonkey使用Rails 3示例更新了代码,这显然优于此代码。 请查看http://pullmonkey.com/2012/08/11/dynamic-select-boxes-ruby-on-rails-3/