Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails select_tag with ajax action (Rails 3 and jQuery)

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!

like image 754
Don Tomato Avatar asked Oct 30 '11 14:10

Don Tomato


1 Answers

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

like image 173
rubyprince Avatar answered Oct 22 '22 12:10

rubyprince