基于另一个选择框更新选择框 (Ruby on Rails)

发布于 2024-08-15 11:54:11 字数 239 浏览 4 评论 0原文

我需要一个更完整的示例,了解如何根据 Ruby on Rails 中第二个选择框的结果更新选择框。我已经在此处询问过这个问题。我已经阅读了该帖子的反馈,但没有任何运气弄清楚这一点,而且我已经尝试了几个小时。有人知道更好(更完整)的例子吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

关于从前 2024-08-22 11:54:11

这通常是在 Javascript 中处理的。我不太喜欢编写 Javascript 代码,因此我在应用程序中为此所做的是使用 form_observer(Rails 助手,它使用 Prototype Javascript 库来监视表单的输入更改)并更新包含以下内容的 HTML 中的 DIV:第二个选择框,基于 AJAX 调用的结果。由于 AJAX 与我的服务器通信,我可以在 Ruby 中编写任意复杂的逻辑来呈现新的 HTML。

示例代码:

#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>

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文