Ruby subclass filter

Hey! I might have misunderstood the subclass, but I have a Person model and I have an attribute called "age", so

Person.first.age #=> '20'

Now I want to have a model in which people are mostly over 55 years old, so I know that I can have a class: Senior class <Person end

But how can I “pre-filter” the senior class so that every object belonging to this class is age> = 55?

Senior.first.age #=> 56

Update1: Therefore, say that I have a company, and many people, and Person belongs to the company, therefore Company.first.people # => ["Jack", "Kate"]

If Jack's age is> 55, then he will work then: Company.first.seniors # => "jack"

Or

Company.first.people.s Senior (s) # => "jack"?

, named_scope , , , named_scope Person. , . - , activerecord ( ), ? , "" , ?

2 , , : 55 Company.first.people.detect {| | p.age > 54}

, , , > 54, , .

!

+3
3

class Person < ActiveRecord::Base
  named_scope :seniors, :conditions => ['age >= ?', 55]
end

Person.seniors.first.age #=> 83
+7

.

class Person
  def self.abstract_class?
    true
  end
end

class Junior < Person
  set_table_name "people"
  default_scope :conditions => "people.age < 55"
end

class Senior < Person
  set_table_name "people"
  default_scope :conditions => "people.age >= 55"
end

, . , , "", RTI Rails.

+3

I don't know how to do this using a subclass, but you can do it using a class method, as shown below.

class Person < ActiveRecord::Base
  def self.senior
    find(:all, :conditions=>["age>=?"], 55)
  end
end

and you can call it from any controller, as shown below.

senior_age = Person.senior.first.age unless Person.senior.blank?
0
source

Source: https://habr.com/ru/post/1738934/


All Articles