【问题标题】:How to call helper method through select_tag如何通过 select_tag 调用辅助方法
【发布时间】:2013-05-20 07:55:32
【问题描述】:

我正在尝试从 select_tag 调用辅助方法。我试过这个:

<%= select_tag(:themes, options_for_select({"Black" => "compiled/styles", "Green" => "compiled/styles2"})) %>

当我输入 alert(this.options[this.selectedIndex].value) 而不是调用方法时,它可以工作。如何更改我的代码以根据需要调用该方法?

编辑

我的application.js上有这个

$(document).ready(function() {
   $('#display_themes').change(function(){
       $.ajax({url: '<%= url_for :controller => 'application', :action => 'set_themes()', :id => 'this.value' %>',
               data: 'selected=' + this.value,
               dataType: 'script'
       }) 
   })
});

在控制器中我有 set_themes 方法

def set_themes()
      @themes = params[:id]
      respond_to do |format|
        redirect_to '/galleries'
        format.html # index.html.erb
        format.xml  { render :xml => @themes }
    end
end

现在的问题是@themes 仍然为空,即使我更改了下拉菜单

Routes.rb

match '', :controller => 'application', :action => 'set_themes()'

【问题讨论】:

  • 显然 remote_function 在 Rails 3 中不起作用
  • 你能说明set_themes是如何初始化的吗?它做了什么?
  • 请查看编辑后的版本。谢谢:)

标签: ruby-on-rails-3 onchange helper html-select


【解决方案1】:

路由到application#set_themes

match '/set_themes', to: 'application#set_themes', as: :set_themes

完成后,只需将 ajax 中的 url 定向如下:

$.ajax({url: "<%= set_themes_path %>",

它应该是 @themes = params[:selected] 根据您在 application.js 中尝试执行的操作。

【讨论】:

  • 是的,我忘了说我已经删除了:onchange => set_themes。我认为问题出在路线上,因为我的路线是这样的:match '', :controller => 'application', :action => 'set_themes()' without params。如何用参数路由它?请查看已编辑的版本 3 以查看 set_themes 功能。并感谢您的回答:-) 非常感谢
  • 请编辑您的问题以在 routes.rb 中显示您的相关路线,并编辑以将@themes 设置为params[:id],并在@ 中适当更改引号987654327@.
  • 我已经编辑了我的问题,更改了报价。我应该将函数 set_themes 更改为 params[:id] 吗?因为我只想从作为参数的下拉列表中将@themes 设为我的值。
  • @themes = params[:id]。您的代码现在有点混乱,所以我只是指出可能不一定能解决您的问题的错误。我已经编辑了我的答案以适合您当前的问题。如果您编辑整个问题以仅显示当前代码并准确描述您希望做什么,这也会有所帮助。
  • @takodil,我再次编辑了我的答案。希望这一次@themes 会有一个价值。如果没有,请检查浏览器的开发者工具,看看是否有任何 ajax 调用的 javascript 错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-27
  • 2019-06-05
  • 1970-01-01
  • 1970-01-01
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多