brainspec / enumerize

Enumerated attributes with I18n and ActiveRecord/Mongoid support
MIT License
1.72k stars 190 forks source link

Enumerize attribute not serializing correctly for false boolean value in PostgreSQL #430

Closed issei-m closed 11 months ago

issei-m commented 1 year ago

Hello,

I am encountering an issue while using Enumerize with PostgreSQL, and would appreciate your guidance in resolving it. The details of the issue are as follows:

Bug:

When an Enumerize attribute, which holds a boolean value in PostgreSQL, is set to false, a SQL error occurs upon saving.

System Details:

Steps to Reproduce:

# ActiveRecord
class User < ActiveRecord::Base
  enumerize :newsletter_subscribed, in: { subscribed: true, unsubscribed: false }
end

create_table "users", force: :cascade do |t|
  t.boolean "newsletter_subscribed", default: true, null: false
end

User.create!(newsletter_subscribed: true) # Works when set to true
User.create! # Works because the default value is true
User.create!(newsletter_subscribed: false) # Error when set to false

Details:

The error only occurs when the value is false. Here are the executed SQL statements:

INSERT INTO "users" ("newsletter_subscribed") VALUES ($1) RETURNING "id" [["newsletter_subscribed", true]]
INSERT INTO "users" ("newsletter_subscribed") VALUES ($1) RETURNING "id" [["newsletter_subscribed", "unsubscribed"]]

As seen above, the value isn't serialized to the DB-specific value (false) when unsubscribed (false).

This error seems to have started after the merge of PR: https://github.com/brainspec/enumerize/pull/424, and it appears to be caused by the cast method. Although I'm not an expert on this gem, renaming the cast method seems to make it work as expected anyway, suggesting that the naming could be the issue. Interestingly, ActiveModel also has a method with the same name, which may or may not be related: https://github.com/rails/rails/blob/v7.0.6/activemodel/lib/active_model/type/value.rb#L45-L47

I look forward to your feedback on this issue.

Best Regards

nashby commented 11 months ago

@issei-m hey! Thanks for detailed bug report! I've pushed a fix to master, could you please check if it works for you?