【问题标题】:How to access view helpers from RJS helpers in Ruby on Rails?如何从 Ruby on Rails 中的 RJS 助手访问视图助手?
【发布时间】:2011-06-27 17:01:20
【问题描述】:

我有一些常见的 RJS 位,我在多个 RJS 文件中重复,因此想将其放入帮助程序中。

我向 app/helpers/application_helper.rb 添加了一个方法,就像我通常为 html.erb 文件添加的方法一样。该方法有效,只是它不能调用 RJS 文件可以调用的视图助手。

在 RJS 文件中起作用的行之一是:

notices = flash.collect { |type,msg| content_tag(:p, msg, :class => type) }

但是无法从 RJS 助手访问 content_tag。为什么不呢,我如何从那里访问它?

【问题讨论】:

    标签: ruby-on-rails-3 unobtrusive-javascript rjs


    【解决方案1】:

    这样的事情怎么样?

    #application_helper.rb
    def view_helpers
      ActionController::Base.helpers
    end
    
    def do_it
      view_helpers.content_tag :div, :class => 'yes'
    end
    

    您也必须在从 rjs 调用的任何方法中使用 view_helpers,这不是很好,但我在模型中尝试过(仅在 2.3 和 3.1 中获得项目)并且有效...

    【讨论】:

      猜你喜欢
      • 2015-03-03
      • 2011-10-05
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      • 2011-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多