ruby - Where is Person and not Person::Single -


lets have 3 classes

person  person::single < person  person::married < person 

lets have two persons single => person::single

then 2 persons when do:

person.all.count => 2 

but goal persons type person , not person::single or person::married

what tried is:

person.where(type: person.to_s) => 2 

but returns 2 because person::single , person::married inherit person

what can instead? there example way ::single , ::married have same methods person not same type? thanks

since marked rails tag, assume person class activerecord model. there more information missing, assume don't know ;)

your person class inherits activerecord methods, example "all", , person::single (and ::maried) inherit through person.

so, naturally, when person.all regular <#activerecord>.all method, not know , not care ::single , ::maried.

what can dynamically setting default_scope, based on class name of calling .all, or .where or whatever on.

class person < activerecord::base   ...    def self.default_scope     scope = if self.name == person.sti_name       where(:type => person.sti_name)     else       nil     end      scope   end  end 

this scope where(:whatever => x) queries.

however, asuming have attribute called "type" person model (column in database).

edit: holger pointed out, there magic involved rails sti. still think viable set default scope, should skip setting scopes single , married. if don't need default scope, should try person.where(:type => person.sti_name) or person.where(:type => person.name) since rails asserts class name sti_name if class inherits activerecord::base.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -