Sou*_*amy 12
您可以在模块中编写可重用的方法,并包含在必要的模型中.
在lib/reusable.rb中创建一个文件
module Reusable
def reusable_method_1
puts "reusable"
end
def reusable_method_2
puts "reusable"
end
end
Run Code Online (Sandbox Code Playgroud)
让我们说如果你想在用户模型中使用它
class User < ActiveRecord::Base
include Reusable
end
Run Code Online (Sandbox Code Playgroud)
并确保在application.rb中为lib /目录启用了autoload_path
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(#{config.root}/lib)
Run Code Online (Sandbox Code Playgroud)
服务器启动时的活动记录扩展
# 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
Run Code Online (Sandbox Code Playgroud)
您需要对名为“Concerns”的 Rails 约定进行一些研究。内幕如下:在您的应用程序目录中创建名为关注点的子目录。在应用程序/关注点中创建模块并将该模块包含在所有模型中。将 app/concerns 的路径添加到 config/application.rb 中的 config.autoload_path 中。
在您执行任何操作之前,我很好奇所有模型中都需要包含哪种方法?我们正在讨论多少种模型以及您想要解决什么问题?
| 归档时间: |
|
| 查看次数: |
7048 次 |
| 最近记录: |