I'm in need of a more complete example on how to update a select box based on the results of a second select box in Ruby on Rails. I asked about this already here. I've read through the feedback from that posting, but am not having any luck figuring this out, and I've been trying for hours. Anybody know of a better (and more complete) example?
+1
A:
This is generally handled in Javascript. I don't particularly enjoy coding Javascript, so what I do for this in my application is to use a form_observer (a Rails helper which uses the Prototype Javascript library to watch your form for input changes) and have update a DIV in the HTML containing the second select box, based on the results of an AJAX call. Since AJAX talks to my server, I can write arbitrarily complex logic in Ruby to render the new HTML.
Example code:
#goes in view
<%= Code to render the first list box. %>
<%= render :partial => 'second_list_box_partial', :locals => {:selected = insert_magic_here } %>
<%= observe_field(:first_list_box,
:url => { :action => :second_box_ajax }),
:frequency => 0.5,
:update => :second_list_box_div,
:with => %Q| 'value=' + $('first_list_box').value; |
%>
#goes in controller
def second_box_ajax
first_box_value = params[:value]
#magic goes here
@selected = #more magic
render :partial => 'second_list_box_partial', :locals => {:selected => @selected}, :layout => false
end
#goes in partial
<div id="second_list_box_div">
Actual code to render list box goes here.
</div>
Patrick McKenzie
2009-12-18 04:51:22
thanks! I'm going to test this code out right now and get back to you...
Kara
2009-12-18 04:54:34
alright, I'm getting an error that says "odd number list for Hash" and it's pointed the the end of the ":selected" in the view. Plus I have no idea what insert_magic_here is. Is that something built into Ruby?
Kara
2009-12-18 05:00:45