Skip to content

Instantly share code, notes, and snippets.

@rockkhuya
Created February 17, 2014 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rockkhuya/9044740 to your computer and use it in GitHub Desktop.
Save rockkhuya/9044740 to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment