Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - using enum in a .where query

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.

like image 293
user4584963 Avatar asked Apr 07 '16 21:04

user4584963


People also ask

How to use enum in Rails model?

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.

How to add enum column Rails migration?

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!

Does Ruby have enums?

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.


1 Answers

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.

like image 52
Gustavo Rubio Avatar answered Oct 16 '22 16:10

Gustavo Rubio