Rails 在 ActiveRecord::Base 中添加方法

sec · June 06, 2017 · Last by sec replied at June 06, 2017 · 1417 hits

请问如何简化代码将所有 Model 中共用的 def self.xx 方法添加到ActiveRecord::Base 里面?

class User < ActiveRecord::Base
...
  #def self.xx
  #end  
end

class Order < ActiveRecord::Base
...
  #def self.xx
  #end
end

建个类在中间

Rails 5 开始,会在 app/models 目录下额外创建一个模型基类 class ApplicationRecord < ActiveRecord::Base,你直接效仿,然后把你的公共逻辑放在里面即可,然后让你所有模型继承这个 ApplicationRecord

Reply to jasl

目前用的 Rails 4.2,model 均继承自 ActiveRecord::Base,Rails 5 之后,才开始继承自 ApplicationRecord。

Reply to sec

ApplicationRecord 长这样

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end

这个是把最佳实践放进新项目的模板里,跟用 Rails 几无关

Reply to jasl

明白了,谢谢 jasl

sec closed this topic. 06 Jun 18:02
You need to Sign in before reply, if you don't have an account, please Sign up first.