简体   繁体   中英

How to add a method to a Ruby on Rails class that operates on a collection/criteria of objects?

I know that I can create an instance method to operate on a particular instance of class and a class method to operate on the class itself. I also know that I can define scopes to select a group of objects based on some criteria I specify.

However, in my case, I have a field date_of_last_approval and I want to take an initial set of objects (pops) and then filter down until I find the oldest and then extract that field. With scopes and the AndAnd gem, I created a class method like this:

def self.oldest_approval_date(pops)
  oldest = pops.which_are_compliant.oldest_state_change.first
  oldest ? oldest.current_compliance_state_date : nil
end

which I can call as x = Pop.oldest_approval_date(user.pops) .

However, it seems to me that I should be able to define a method that operates at the tail end of a chain of scopes, so I could have:

x = user.pops.oldest_approval_date

I found one article which seems to address this but I was surprised there is not more discussion around this. What is the general philosophy regarding designing methods like this and if it is acceptable what is the best form?

the all class method returns the current scope so you can use that. You can use self for the same effect. But the best of all is that you can just call an existing scope which should work as well.

def self.oldest_approval_date
  oldest = which_are_compliant.oldest_state_change.first
  oldest ? oldest.current_compliance_state_date : nil
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM