updating a select box based on another (Ruby on Rails)

北城余情 提交于 2020-01-23 17:54:26

问题


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:


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>


来源:https://stackoverflow.com/questions/1925954/updating-a-select-box-based-on-another-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!