Enum field: undefined method `roles' for User:Class
-
What were you trying to do? I was trying to add role to User model as enum field
-
What did you end up with (logs, or, even better, example apps are great!)?
This is my migration for creating user roles
class AddRoleToUser < ActiveRecord::Migration[7.1]
def up
create_enum :user_roles, %w[admin user]
add_column :users, :role, :enum, enum_type: :user_roles, default: 'user', null: false
end
def down
remove_column :users, :role
execute <<-SQL
DROP TYPE user_roles;
SQL
end
end
this is what was generated after running rails generate administrate:install non-necessary info omitted.
class UserDashboard < Administrate::BaseDashboard
# ATTRIBUTE_TYPES
# a hash that describes the type of each of the model's fields.
#
# Each different type represents an Administrate::Field object,
# which determines how the attribute is displayed
# on pages throughout the dashboard.
ATTRIBUTE_TYPES = {
id: Field::Number,
# ...
role: Field::Select.with_options(searchable: false, collection: lambda { |field|
field.resource.class.send(field.attribute.to_s.pluralize).keys
}),
# ...
}.freeze
ActionView::Template::Error (undefined method `roles' for User:Class):
23: f.select(
24: field.attribute,
25: options_for_select(
26: field.selectable_options,
27: field.data,
28: ),
29: include_blank: field.include_blank_option
app/dashboards/user_dashboard.rb:27:in `block in <class:UserDashboard>'
This is what I have received after running this auto-generated code. I believe this is error-phone.
I could fix it with adding the following lines to rails model.
def self.roles
{ admin: :admin, user: :user }
end
I believe we should follow the principle of least surprise. Error message should contain info that you ought to define ROLES constant or define class method roles, but it should be verbose and easy to understand. I think it can be improved and I can handle fix, thank you for the great gem :smiley:
- What versions are you running?
- Rails 7.1.2
- administrate 0.19.0
Ah yeah, that's annoying. Do you think you'd be able to contribute a fix? Perhaps something about showing a better error message?
Does Rails expect having a roles class method, though?
Yes, I can handle it, seems like something small to fix
Does Rails expect having a roles class method, though?
I've never seen them reserving this word, but need to research that