Today I Learned

hashrocket A Hashrocket project

Add a Suffix to ActiveRecord Enums

Today I learned you can add suffixes to ActiveRecord Enums. I knew it was possible to prefix enums with the _prefix option:

class Answer < ApplicationRecord
  enum selection: {yes: "yes", no: "no", idk: "i don't know"}, _prefix: true
end

And you get helper methods like answer.selection_yes?, but that reads a little awkwardly. I think it reads better as answer.yes_selection?. Turns out you can do this with _suffix:

class Answer < ApplicationRecord
  enum selection: {yes: "yes", no: "no", idk: "i don't know"}, _suffix: true
end

answer = Answer.new selection: "yes"
answer.yes_selection? # => true
answer.no_selection? # => false

ActiveRecord::Enum Docs

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.