在Rails应用程序中放置多个模型所需的辅助方法的位置?

时间:2013-01-03 18:13:57

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

举个例子:

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

1 个答案:

答案 0 :(得分:2)

我通常在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