0

Here is my model defination:

class OrderFrequency < ApplicationRecord
  self.table_name = "order_frequencies"
  enum frequency_unit: { hour: 1}

end

and migration

class CreateOrderFrequencies < ActiveRecord::Migration[5.2]
  def change
    create_table :order_frequencies do |t|
      t.string :value
      t.integer :unit
      t.timestamps
    end
  end
end

So how do I assign unit attribute with enum of frequency_unit?

I cannot do

OrderFrequency.create(value: 'value 123', unit: OrderFrequency.frequency_unit.hour)

What is the correct way to use frequency_unit enum for the unit attribute?

Thanks

1 Answer 1

1

See the official documentation for ActiveRecord::Enum -- the idea isn't to have two attribute names (unit and frequency_unit); you should only have one. (After all, it's the same thing!)

Let's change your model to:

class OrderFrequency < ApplicationRecord
  # Note: Specifying the (default) table_name here is also redundant
  enum unit: { hour: 1 }
end

Now you can create a record via:

OrderFrequency.create(
  value: 'value 123',
  unit: OrderFrequency.units['hour']
)

Or even (!!) by just writing:

OrderFrequency.create(
  value: 'value 123',
  unit: 'hour'
)

The key idea with ActiveRecord::Enum is that in the database the value is stored as an integer, but in the application (99% of the time) you can work with human-friendly Strings - i.e. "hour" rather than 1.

If for some reason you need to retrieve a list of all known units, you can do this with:

OrderFrequency.units.keys #=> ['hour']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.