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]
endActiveRecord 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
endNow 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
endHow 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
Keep reading

Fix mise GitHub Rate Limit with a Token
mise makes unauthenticated GitHub API calls by default. When you hit the rate limit installing tools, a personal access token (no scopes required) fixes it permanently.

How to solve Deployment Failure-`assets:precompile`
I was trying to deploy rails 6 app on ec2 server using capistrano when precompile failure lead to whole deploymentt failure. I had to uninstall cmdtest and install yarn

How to Sort an Array of Objects in JavaScript
How to Sort an Array of Objects in JavaScript

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.