jmasterx jmasterx - 4 months ago 13
Ruby Question

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?

Answer

Maybe it makes extract the planet as another model?

class Planet < ActiveRecord::Base
  enum type: %w(earth mars jupiter)
end

class PlanetEdge < ActiveRecord::Base
  belongs_to :first_planet, class_name: 'Planet'
  belongs_to :second_planet, class_name: 'Planet'
end

You can create a PlanetEdge by using accepts_nested_attributes_for:

class PlanetEdge < ActiveRecord::Base
  belongs_to :first_planet, class_name: 'Planet'
  belongs_to :second_planet, class_name: 'Planet'

  accepts_nested_attributes_for :first_planet
  accepts_nested_attributes_for :second_planet
end

PlanetEdge.create(
  first_planet_attributes: { type: 'mars' },
  second_planet_attributes: { type: 'jupiter' }
)