Enum is not working in Rails 5, Active Support 5.2.2, enum set returns empty array always
cesar82 opened this issue · 7 comments
I created a new project with rails 5 and added the gem, I can save the enum correctly in the db but when I load the model from db, the attribute only returns #<Enumerize::Set {}> empty.
I tried with and without multiple and same behavior.
@cesar82 hey, sorry for the late response but can you please provide sample app that reproduce the issue? I'm using it in various Rails 5 projects and it works as expected.
@nashby I encounter the same issue using rails 5.0.7.2, enumerize 2.3.1.
# db/migrate/20190521060849_add_administrator_roles.rb
class AddAdministratorRoles < ActiveRecord::Migration[5.0]
def change
add_column :administrators, :roles, :string
end
end
# app/models/administrator.rb
class Administrator < ApplicationRecord
extend Enumerize
...
serialize :roles, Array
enumerize :roles, in: [:admin, :user_support], multiple: true
end
Administrator.first.roles
initially returns #<Enumerize::Set {}>
. I then run Administrator.first.roles << :admin
, Administrator.first.save
, after which Administrator.first.roles
still returns #<Enumerize::Set {}>
.
@sedubois the thing is that you're calling save on a new object which is not modified with :admin
changes. I'm pretty sure that following will work:
admin = Administrator.first
admin.roles << :admin
admin.save
Administrator.first.roles # => [:admin]
OK I think this is some feature/bug from ActiveRecord. It works when passing the data to update
directly:
Administrator.first.update(roles: [:admin])
Administrator.first.roles
=> #<Enumerize::Set {admin}>
I first tried the <<
operator as suggested in the README but now that I check again, that example was for POROs ("Array-like attributes with plain ruby objects"). It might be helpful to enhance the README with an ActiveRecord example of how to actually update a record. Pity <<
doesn't seem to work.
Would like an update on the subject if anyone has details of why is this bug is caused