【问题标题】:Rails and Rake task - How to call a Rails method inside a custom class defined in a rake task fileRails 和 Rake 任务 - 如何在 rake 任务文件中定义的自定义类中调用 Rails 方法
【发布时间】:2012-12-28 15:45:40
【问题描述】:

我在"Rails Root"/lib/tasks/example.rake中有以下代码:

task :example_task => :environment do
  e = Example.new
  e.example_method
end

class Example
  def example_method
    select_tag 'Example'
  end
end

当我在 rake 任务中调用 e.example_method 时,我收到错误 "undefined method 'select_tag' for #<Example:0x39f58b0>"

select_tag 是 Rails 方法:http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-select_tag

如何使select_tag 通话有效?

【问题讨论】:

  • 你只需要需要你需要的助手。请检查这个[问题][1]。 [1]:stackoverflow.com/questions/1450112/…
  • select_tagActionView 中的辅助方法之一,为什么您的 Rake 任务会调用与视图相关的任何方法?只是好奇

标签: ruby-on-rails ruby rake


【解决方案1】:

您需要要求帮助程序您尝试使用的方法。对于select_tag,您需要要求ActionView

【讨论】:

    【解决方案2】:

    您可以:

    通过辅助变量访问辅助方法:

    helper.content_tag :li, "Helola" 
    => "<li>Helola</li>"
    

    或需要所需的助手

    require "#{RAILS_ROOT}/app/helpers/some_helper.rb"
    include SomeHelper
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      • 2018-12-07
      相关资源
      最近更新 更多