Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same enum values for multiple columns

I need to do something like this:

class PlanetEdge < ActiveRecord::Base
  enum :first_planet [ :earth, :mars, :jupiter]
  enum :second_planet [ :earth, :mars, :jupiter]
end

Where my table is a table of edges but each vertex is an integer.

However, it seems the abvove is not possible in rails. What might be an alternative to making string columns?

like image 369
jmasterx Avatar asked Jun 22 '15 13:06

jmasterx


People also ask

Can enum hold multiple values?

The Enum constructor can accept multiple values.

Can two enums have the same value Java?

Two enum names can have same value.

Can we add constants to enum without breaking existing code?

4) Adding new constants on Enum in Java is easy and you can add new constants without breaking the existing code.

What is enum constant?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.


1 Answers

If you're running rails 5.0 or greater as per http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html

You can use the :_prefix or :_suffix options when you need to define multiple enums with same values. If the passed value is true, the methods are prefixed/suffixed with the name of the enum. It is also possible to supply a custom value:

class Conversation < ActiveRecord::Base
    enum status: [:active, :archived], _suffix: true
    enum comments_status: [:active, :inactive], _prefix: :comments
end

With the above example, the bang and predicate methods along with the associated scopes are now prefixed and/or suffixed accordingly:

conversation.active_status!
conversation.archived_status? # => false

conversation.comments_inactive!
conversation.comments_active? # => false
like image 58
Wojciech Szymanski Avatar answered Sep 25 '22 01:09

Wojciech Szymanski