【问题标题】:Where to put helper methods needed in multiple models in a Rails app?在 Rails 应用程序中,多个模型所需的辅助方法应该放在哪里?
【发布时间】:2013-01-03 18:13:56
【问题描述】:

举个例子:

module ModelHelper
  def self.special_function(some_parameter)
    do_some_special_thing
  end
end

class Student < ActiveRecord::Base
  def to_special
    ModelHelper.special_function(a_variable_of_here)
  end
end

class Teacher < ActiveRecord::Base
  def to_special
    ModelHelper.special_function(another_variable_of_here)
  end
end

我应该把model_helper.rb放在哪里?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 activerecord ruby-on-rails-3.2


    【解决方案1】:

    我通常在 lib 中创建一个文件并包含它。 lib/special_model.rb 之类的东西:

    module SpecialModel
       included do
         def to_special
           do_some_special_thing
         end
       end
    end
    

    然后在 app/models/student.rb 中:

    class Student
      include SpecialModel
    end
    

    在使用模块时,您可能还想查看 ActiveSupport::Concern 以获得一些 rails 帮助:

    http://api.rubyonrails.org/classes/ActiveSupport/Concern.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      • 1970-01-01
      • 2011-03-22
      • 2018-03-12
      相关资源
      最近更新 更多