Form.select with :onChange event help

Hey everyone,

As a quick elaboration: I’m trying to make an Admin panel which lists
the CRUD actions for several models. The use case calls for a drop-down
box for the user to be able to select the object they want to perform an
action on and then links to different actions.

What I started with is the following:

<% form_for :major do |form| %>
<%=
@majors = Major.find(:all, :order => “name” ).map {|u| [u.name, u.id] }
form.select(:major_id, @majors)
%>
<%= link_to ‘Show’, :action => ‘show’, :id => :major_id %>
<%= link_to ‘Edit’, :action => ‘edit’, :id => :major_id %>
<%= link_to ‘Destroy’, { :action => ‘destroy’, :id => :major_id },
:confirm => ‘Are you sure?’, :method => :post %>
<% end %>

What I want it to do is take the selected id and pass it to the action,
but so far it either interprets ‘major_id’ literally as the id or passes
the entire array from the drop-down box. Needless to say, it hasn’t been
working.

What someone has suggested I do is:

  1. Use JS for the onchange event on the dropdown, and have it update the
    link hrefs.
  2. Have all the actions links load via RJS on the onchange event.

I’m not familiar with RJS at all really, but I looked at some posts
about similar problems and came up with the following:

<% form_for :major do |form| %>
<%= form.collection_select(:major, Major.find(:all, :order => ‘name’),
:id, :name, {:prompt => true}, :onChange => remote_function(:url =>
‘list’, :with => “’:id=’ + this.value”) ) %>
<%= link_to ‘Show’, :action => ‘show’, :id => params[:id] %>
<%= link_to ‘Edit’, :action => ‘edit’, :id => params[:id] %>
<%= link_to ‘Destroy’, { :action => ‘destroy’, :id => params[:id] },
:confirm => ‘Are you sure?’, :method => :post %>
<% end %>

Unfortunately, it still appears to be a failure. I also saw mention to
using this, but am even less sure of how it works:

:onChange => "new Ajax.Request(this.value, {asynchronous:true,
evalScripts:true})

If you’ve got some ideas on how to get this to work or could if you can
help clear up what I am doing wrong, it would be really helpful. Thanks
in advance!

Honestly I’m not sure what your trying to accomplish?

I would be so bold as to suggest though that the solution is not
technical.
Rather that you should change your design.

Use the observe_field function to setup a AJAX call to the back end to
populate the area of the form that contains the details of the object
and move the object details to a partial. You can also try assigning
the value of the select field to a class variable like @major_id in
the backend and use that in your link_to calls as :id=>@major_id
I don’t think using plain link_to will result in a form submit action
that is required for you to get the value of the select field. Look
at the messages in the server console to see what is getting passed
back to the server.

On Apr 5, 11:26 pm, Adam G. [email protected]