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

时间:2011-10-30 14:41:48

标签: ruby-on-rails ruby-on-rails-3

我有以下选择列表。

<%= select_tag "project_id", options_from_collection_for_select(@projects, "id", "title") %>

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

<%= select_tag "version_id", options_from_collection_for_select(??project.versions??, "id", "title") %>

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

1 个答案:

答案 0 :(得分:25)

<强>的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)" %>
<div id="versionsDiv">
  <%= render :partial => 'versions', :object => @versions %>
</div>

部分:_ version.html.erb

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

还在routes.rb

中添加/update_versions的路由
match "/update_versions" => "<controller>#update_versions"

在这里,您应该用控制器的名称替换<controller>

我没有测试过代码,因此可能存在错误。

<强>更新

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