code-quality

How to have same enum values for multiple columns in rails

How to have same enum values for multiple columns in rails

How to have same enum values for multiple columns in rails

Sometimes we may need to share same enum values in multiple columns in rails. For eg: I may have a model named file that can either be of type transfer or new, and can be in transfer, review or approved state. I now have both state and type as enum and my modal looks like this:

class File < ActiveRecord::Base
  enum :state [ :transfer, :review, :approved]
  enum :type [ :transfer, :new]
end

ActiveRecord provides us some helper methods like bang and predicate methods for enums and in this case File.last.transfer! would probably not work as we have two transfer to resolve to, hence this won’t work. As mentioned in official doc we can make it work using prefix or suffix with enum. Above code can be fixed as:

Using suffix

We can either pass boolean or some value so that helper methods are still valid.

class File < ActiveRecord::Base
  enum :state [ :transfer, :review, :approved], _suffix: :step  #providing some value for suffix
  enum :type [ :transfer, :new], _suffix: true, _suffix: true #providing boolean value
end

Now our helper methods would look like:

file.transfer_step?, file.transfer_step!
file.transfer_type?, file.transfer_type!

Define prefix

class File < ActiveRecord::Base
  enum :state [ :transfer, :review, :approved], _prefix: :step  #providing some value for suffix
  enum :type [ :transfer, :new], _suffix: true, _prefix: true #providing boolean value
end

How this works is similar to above except defined words will come at first in helper methods.

Now our helper methods would look like:

file.step_transfer?, file.step_transfer!
file.type_transfer?, file.type_transfer!

References:

https://stackoverflow.com/questions/30981350/same-enum-values-for-multiple-columns/38441150#38441150 http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html

About the author

Prakash Poudel Sharma

Engineering Manager · Product Owner · Varicon

Engineering Manager at Varicon, leading the Onboarding squad as Product Owner. Eleven years of building software — first as a programmer, then as a founder, now sharpening the product craft from the inside of a focused team.

Keep reading

More on this

Join the conversation0 comments

What did you take away?

Thoughts, pushback, or a story of your own? Drop a reply below — I read every one.

Comments are powered by Disqus. By posting you agree to theirterms.

0:000:00