Self-Submitting Form Selects
By chris on February 21st 2007 in /dev/rails | 225 views
After much scouring of the web and various Rails books I finally figured out how to generate a form select pop-up that self-submits to the page to update content (no Ajax in this... yet).
This goes into the view:
RUBY:
-
<% form_for :user_group, :url => { :controller => :user_group,
-
:action => :select } do |form| %>
-
<%= form.select :id, UserGroup.find( :all, :order => 'name ASC' ).collect { |group| [ group.humanize_name( group.name ), group.id ] }, {}, :onchange => "selectGroup( this );" %>
-
<% end %>
This is the javascript function that gets called when the form select is changed. Goes into the HTML page (or better, an included javascript file):
JAVASCRIPT:
-
function selectGroup( $pSelect )
-
{ location.href = '?user_group_id=' + $pSelect.value; }
This goes into the controller. In my case the function called is "create", yours will probably differ:
RUBY:
-
def create
-
# Check that the group value was passed in. If no value, select a default
-
params[:user_group_id] != nil ? user_group_id = params[: user_group_id] : user_group_id = 1
-
-
# instantiate a group and store the selected id in it so that select item can be selected when next the page is generated
-
@user_group = UserGroup.new
-
@user_group.id = user_group_id
-
...
-
# rest of the logic here
-
...
-
end