I am using enum on a model:
enum status: [:pending, :approved]
I have a uniqueness validation in the model that looks like this:
validates :item_id, uniqueness: { scope: :user_id, conditions: -> { where(status: :approved) }, message: "You already have this item." }
This doesn't work. It will only work if I change :approved
to 1
. I'm confused as to why I can't use the status name here when I can do something like Item.first.update_attributes(status: :approved)
and it works fine.
Various ways to define enum in model We run the migration using rake db:migrate and in our Post model, we need to define the enum as shown in the below example. The enum method expects the column attribute name which it should refer to and the second parameter is a list of values a post status can have.
First of all, you need to create an appropriate migration. Notice that column type is set to integer and this is how Rails keeps enums values in the database. Next step is to declare enum attribute in the model. Run the migrations and that's it!
Enum is a data type that contains a fixed set of constants, usually mapped to integer values. Ruby does not have a built-in Enum type, unlike many other programming languages. Although Enums feature was introduced in Rails 4.1 using some custom implementation.
Use the enum value from the model like so:
where(status: Model.statuses[:approved])
Instead of just the symbol. That way the enum helper method for statuses
will pass the integer value of the enum which will make the filter work. The enum values are actually stored as integers in the DB not as the string representation of the symbols.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With