[Feature Request] Boolean methods for STI models

29 views
Skip to first unread message

Matheus Santana

unread,
May 20, 2016, 4:20:23 PM5/20/16
to Ruby on Rails: Core
From the docs:

class Company < ActiveRecord::Base; end
class Firm < Company; end
class Client < Company; end
class PriorityClient < Client; end

Boolean methods would be something like:

company = Company.find(1)
company.firm?
company.client?
company.priority_client?

What about it?

Allen Madsen

unread,
May 20, 2016, 6:07:33 PM5/20/16
to rubyonra...@googlegroups.com
Typically, when you use STI models it's because the data will be the
same, but the behavior will vary. Because a different class is loaded
based on the STI type, you can handle behavior polymorphically. So
rather than:

if company.firm?
do_thing(company)
end

You would instead do:

company.do_thing

Then each subclass of company would implement the correct behavior for
that case.

For the behavior you described, you may be better served with Rails
enum support: http://api.rubyonrails.org/v4.1/classes/ActiveRecord/Enum.html
Allen Madsen
http://www.allenmadsen.com
> --
> You received this message because you are subscribed to the Google Groups
> "Ruby on Rails: Core" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to rubyonrails-co...@googlegroups.com.
> To post to this group, send email to rubyonra...@googlegroups.com.
> Visit this group at https://groups.google.com/group/rubyonrails-core.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages