Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Enum return integer value, not string representation

I have a table which contains an integer based column (status) which I'm using for an enum attribute within the Rails model.

At the moment of doing:

Post.select(:id, ..., :status)

Defined as:

enum status: { inactive: 0, active: 1, ... }

It returns everything as expected, but the status column is returned in its string value as inactive, active, etc. But I need it as an integer.

How can I get that?

I'm currently just using ActiveRecord::Base.connection.execute and passing a raw query:

ActiveRecord::Base.connection.execute('select id, ..., status from posts')
like image 837
Karol Karol Avatar asked Sep 20 '25 05:09

Karol Karol


1 Answers

Have you tried this?

# Rails < 5
post = Post.find(123)
post.read_attribute(:status)

# Rails >= 5
post = Post.find(123)
post.read_attribute_before_type_cast(:status)
like image 65
Penguin Avatar answered Sep 21 '25 23:09

Penguin