我应该在Rails中将一个方法放在我的所有模型中?
我应该在Rails中将一个方法放在我的所有模型中?
您可以在模块中编写可重用的方法,并包含在必要的模型中。
在lib / reusable.rb中创建一个文件
module Reusable
def reusable_method_1
puts "reusable"
end
def reusable_method_2
puts "reusable"
end
end
让我们说如果你想在用户模型中使用它
class User < ActiveRecord::Base
include Reusable
end
并确保在application.rb中为lib /目录启用了autoload_path
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(#{config.root}/lib)
服务器启动时的活动记录扩展
# config/initializers/core_extensions.rb
class ActiveRecord::Base
# write ur common base code here
def self.per_page
@@per_page ||= 10
end
def self.pagination(options)
paginate :per_page => options[:per_page] || per_page, :page => options[:page]
end
end
有多种方法可以实现这一目标
您将要对名为“Concerns”的Rails约定进行一些研究。这是下行:在app目录中创建名为Concer的子目录。在应用程序/关注点中创建您的模块,并在所有模型中包含该模块。将app / concerns的路径添加到config / application.rb中的config.autoload_path。
在你做任何这些之前,我很好奇所有模型中需要包含哪种方法?我们谈了多少型号,你想解决什么问题?