【问题标题】:Make a Select Box that Calls a Method创建一个调用方法的选择框
【发布时间】:2012-04-22 21:00:48
【问题描述】:

我有一个带有标签的工作报告的 rails 应用程序。在 Report/Index.html.erb 中,我希望用户能够通过选择标签对报告进行排序。他们一次只能选择一个标签,所以我觉得选择框效果最好。我目前有这个:

<%= select("preferences", :tag_with, 
 ["Politics", "Technology", "Entertainment", "Sports", "Science", "Crime", 
 "Business", "Social", "Nature", "Other"], :prompt => "Filter Feed by:" )%>

我有一个有效的首选项控制器,它带有一个方法调用tag_with 来更新当前标签。但是,此代码仅生成选择框。我希望当用户选择其中一个标签时,它会从首选项控制器中调用 tag_with 方法。

我生成了一系列完成任务的link_to 行,但是我真的想要一个选择框。

<%= link_to "Politics", :action => "tag_with", :tag => "Politics", :controller =>"preferences" %>
<%= link_to "Entertainment", :action => "tag_with", :tag => "Entertainment", :controller =>"preferences" %>
<%= link_to "Science", :action => "tag_with", :tag => "Science", :controller =>"preferences" %>
<%= link_to "Technology", :action => "tag_with", :tag => "Technology", :controller =>"preferences" %>

每个标签以此类推。这工作正常,但体积庞大且不可取。有没有办法通过选择框做同样的事情?

【问题讨论】:

  • 你试过只绑定选择框的onchange事件吗?
  • 我该怎么做呢?我不确定将 onChange 事件绑定到什么。我已经尝试过 onChange => link_to ... 但这不起作用。
  • 首先这应该不显眼地完成(给选择一个 id 并在 javascript 中处理事件)。有关更多信息,请参阅railscasts.com/episodes/205-unobtrusive-javascript 和unobtrusive javascript rails 的谷歌搜索结果。什么版本的 Rails?您使用的是 Coffee Script 还是仅使用 javascript?让我知道,如果您仍然需要帮助,我会提交完整的答案。
  • 我目前正在使用 JQuery javascript,但是我对这种语言很薄弱。我正在使用 Rails 3.2 版

标签: ruby-on-rails select tags link-to


【解决方案1】:

在您的 reports.js.coffee 文件中,或您想要的任何其他 js 文件中。

jQuery ->
  $('select#preferences').change ->
    $.get 'preferences/tag_with',{ term: $('option:selected', this). val() }

或者,如果您想使用常规 javascript:

$(function(){
  $('select#preferences').change( function() {
    $.get('preferences/tag_with',{term: $('option:selected',this).val()});
  });
});

链接是一个 GET 请求。每当有人进行更改时,jQuery .change() 方法就会触发。 $.get 方法向 URL 发送 GET 请求并可以传递数据(第二个参数)。这些数据成为你的参数哈希,所以在上面的例子中你会得到:

params[:term] #=> the value attribute of whatever option was selected by the user

有关更多帮助,请参阅 .change() 和 $.get() 上的 jQuery 文档。


更新

要刷新页面,最简单的方法是提取要更改为部分的表,假设它名为_report.html.erb。部分应该是这样的:

<div id="report">
  <%= render @report %>
</div>

*注意:render @report 是 render :partial =&gt; 'report' 的缩写。见http://guides.rubyonrails.org/layouts_and_rendering.html*

在您的首选项控制器的 tag_with 选项中,您应该确保设置 @report 对象(或任何其他将数据传送到您的部分的对象)。

然后你应该创建一个名为views/preferences/tag_with.js.erb 的文件并在其中放入类似这样的内容:

$('div#report').html('<%= escape_javascript( render @report ) %>');

这将使用新内容更新报告容器。

【讨论】:

  • 这很好用!但是,它仅在重新加载页面后交换过滤器。有没有办法自动做到这一点?
  • 我似乎在使用 link_to 时得到Processing by ReportsController#index as HTML,但是当我使用 select 时得到Processing by ReportsController#index as *\*。你知道这是什么原因吗?
  • 尝试使用'preferences/tag_with.js' 作为您的网址,看看会发生什么。
  • 它仍然需要刷新。有没有办法通过 JQuery 自动刷新它?甚至在preferences#tag_with 方法中?
  • 哦,对了,页面需要用jQuery刷新。更新待定。
猜你喜欢
  • 2013-05-24
  • 2011-10-06
  • 1970-01-01
  • 2012-11-24
  • 2015-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多