【问题标题】:access custom helper in model在模型中访问自定义助手
【发布时间】:2014-05-13 08:54:54
【问题描述】:

我在我的 ApplicationController 中写了一个小辅助方法,如下所示:

helper_method :dehumanize
def dehumanize (string)
  string.parameterize.underscore
end

现在我想在我的一个模型文件中使用它,但那里似乎不可用。

我也试过:

ApplicationController.dehumanize(title)

在模型中,但它不起作用。

关于如何让它在那里工作的任何线索?

谢谢,

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 model-view-controller


    【解决方案1】:

    模型通常不能/不要/不应该访问控制器中的方法(MVC 约定),但您编写的方法不一定属于控制器 - 最好作为字符串类。

    我建议你编写一个初始化器将dehumanize 添加到String

    \config\initializers\string_dehumanize.rb
    
    class String
      def dehumanize
        self.parameterize.underscore
      end
    end
    

    您需要重新启动服务器/控制台,然后您可以在任何字符串上调用 .dehumanize

    some model:
    def some_method
      string1 = 'testing_the_method'
      string1.dehumanize
    end
    

    【讨论】:

      【解决方案2】:

      Matt 的回答是完全正确的,但为了澄清一点,您要确保在 objects / instances 上调用您的方法,而不是类本身

      例如,您提到您尝试过这个:

      ApplicationController.dehumanize(title)
      

      这永远不会起作用,因为它正在调用未初始化的类的方法,更不用说该类没有该方法。基本上,如果你调用这个方法,你会期待什么?

      方法是使用推荐的方法Matt,或者在你的模型本身上使用一个类方法,这样你就可以直接调用模型的方法:

      #app/models/model.rb
      class Model < ActiveRecord::Base
          def self.dehumanize string
              string.parameterize.underscore
          end
      end
      
      # -> Model.dehumanize title
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-05
        • 1970-01-01
        • 1970-01-01
        • 2011-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多