【发布时间】:2012-02-28 13:41:27
【问题描述】:
我应该在 Rails 中的哪个位置放置一个方法,以供我的所有模型使用?
【问题讨论】:
标签: ruby-on-rails model global
我应该在 Rails 中的哪个位置放置一个方法,以供我的所有模型使用?
【问题讨论】:
标签: ruby-on-rails model global
您可以在模块中编写可重用的方法并包含在必要的模型中。
在 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/concerns 中创建您的模块,并将该模块包含在您的所有模型中。将 app/concerns 的路径添加到 config/application.rb 中的 config.autoload_path。
在您执行上述任何操作之前,我很好奇所有模型中都需要包含哪种方法?我们讨论了多少个模型,你想解决什么问题?
【讨论】: