I'm building a Rails app that will have a very high number of models using single-table inheritance. For the model subclasses, I want to be able to set constant values for things like name
and description
. I know I can set defaults using attribute
, like this:
class SpecialWidget < Widget
attribute :name, :string, default: "Special Widget"
attribute :description, :text, default: "This is an awfully important widget."
end
The advantage here, as I understand it, is that by storing the defaults in the database, I retain the ability to do things use #order
to sort by name, and paginate. But it seems bad to store constants in the database like that. It seems better to use constant methods, like this:
class SpecialWidget < Widget
def name
"Special Widget"
end
def description
"This is an awfully important widget."
end
end
In fact, that's what I was doing originally, but then I read posts like these (one, two, three), which pointed out that then if I wanted to do nice things like sort by the methods, I'd have to load the entire Widget.all
into memory and then do a plain-old Ruby sort.
My application is built quite heavily around these STI models, and I will definitely have to sort by constants like name
. Are the concerns about sorting and pagination significant disadvantages that will cause me to come to regret using methods in the future, or will the difference be negligible? What other disadvantages/problems might I have? I'd really like to be able to use methods instead of storing constants in the database, if possible without crippling my app's performance.