[英]Rails ActiveRecord: Where to define method?
我对Rails的ActiveRecord有疑问。
例如,我有一个Service
模型,而Service
name
为一列。
这是app/model/service.rb
class Service < ActiveRecord::Base
def self.class_method
puts 'This is class method'
end
def instance_method
puts 'This is instance method'
end
end
那我就可以
Service.class_method #=> 'This is class method'
Service.find(1).instance_method #=> 'This is instance method'
这很容易。 但是当我在数组中获得ActiveRecord实例时
Service.where(id: [1,2,3])
我需要像这样的方法
Service.where(id: [1,2,3]).sample_method
def sample_method
self.length
end
但是如何以及在何处定义Active Record Array的方法? 我想像处理其他Service
类或实例一样处理此对象。
谢谢。
您的方法,例如get_count
和get_name
毫无意义……为什么不这样做:
Service.count
Service.find(1).name
诸如count
类的类方法和诸如name
类的实例方法(即数据库列名)都是公共的 -因此您无需定义自己的getter方法。
对于第二个示例,您可以编写以下代码:
Service.where(id: [1,2,3]).map{ |s| s.name }
或等效地:
Service.where(id: [1,2,3]).map(&:name)
但是下面的命令实际上更有效,因为它使用SQL而不是ruby执行计算。 (如果您对我的意思感到困惑,请尝试同时运行两个版本并在日志中比较生成的SQL):
Service.where(id: [1,2,3]).pluck(:name)
首先, where
返回一个ActiveRecord :: Relation对象,而不是一个数组。 它的行为类似于数组,但是继承了更多的加载方法来处理数据/构造用于查询数据库的SQL。
如果要向ActiveRecord :: Relation类添加其他功能,可以执行以下操作:
class ActiveRecord::Relation
def your_method
# do something
end
end
这将需要驻留在有意义的地方,例如lib目录或config / initializers。
这应该允许您做类似的事情
Service.where(id: [1,2,3]).your_method
您可以对任何Ruby类执行类似的操作,例如Hash或Array类。
但是,几乎总有比扩展/覆盖Rails / Ruby源类更好的解决方案...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.