Rails select_tag with ajax action (Rails 3 and jQuery)

只愿长相守 提交于 2019-12-28 11:46:31

问题


I have the following select list.

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

When the user selects an option from the above list, the list below should be populated with values from database based on the above selection.

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

I think i should make use of the onchange event, but i have no idea on how to use it. Someone help me please. Thanks!


回答1:


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);
    }
  });
}

Controller

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

View

<%= 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>

Partial: _version.html.erb

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

Also add a route for /update_versions in your routes.rb

match "/update_versions" => "<controller>#update_versions"

Here, you should replace <controller> with name of the controller.

I havent tested the code, so there may be errors.

Update

PullMonkey has updated the code with Rails 3 example, which is obviously superior than this code. Please checkout http://pullmonkey.com/2012/08/11/dynamic-select-boxes-ruby-on-rails-3/ also



来源:https://stackoverflow.com/questions/7945529/rails-select-tag-with-ajax-action-rails-3-and-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!