Pis7ftw
Pis7ftw

Reputation: 105

Rails/Postgres enum implementation creating records with enum key, not its value

Using Rails 6.1.1

I've created a postgres implementation of enums on rails. However, on record create, the enum column is saving the enums' key, not the value as I would expect.

Migration:

execute "CREATE TYPE member_status_type AS ENUM ('New Member', 'Member Status Not Set')"
add_column :members, :member_status, :member_status_type

MemberEnums.rb

MEMBER_STATUSES = {
new_member: "New Member",
member_status_not_set: "Member Status Not Set"}.freeze

Member Model:

enum member_status: MemberEnums::MEMBER_STATUSES

Member creation:

Member.create!({member_status: MemberEnums::MEMBERS_STATUSES[:new_member]})

Result:

=> #<Member id: 12, member_status: "new_member">

The result I'm expecting should be

=> #<Member id: 12, member_status: "New Member">

Upvotes: 1

Views: 166

Answers (1)

Member Model:

enum status: MemberEnums::MEMBER_STATUSES

By changing the name of enum your desired results will be achieved. This might be happening because you have given the same name for the attribute and the enum

Upvotes: 1

Related Questions