我有一個關於Rails的ActiveRecord的問題。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陣列的方法?我想處理這個對象就像其他Service
類或實例。
謝謝。
更新第一款了。 –