skwidbreth skwidbreth - 4 months ago 9
Ruby Question

Devise - setting default values for new users

I am using Devise for user sign ups in my Rails app. The Users table has a column called

admin
, which is boolean. I would like to set it so that the value of
admin
automatically defaults to
false
for every new user that signs up. I've tried a number of different approaches, but nothing seems to work.

I'm looking for something like this to happen:

class ApplicationController < ActionController::Base

def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :first_name
devise_parameter_sanitizer.for(:sign_up) << :last_name
devise_parameter_sanitizer.for(:sign_up) << :phone
devise_parameter_sanitizer.for(:sign_up) << {:admin => false}
end
end


Although this, as I said, doesn't work. But something like that. Any suggestions would be much appreciated.

Answer

You should set the default value of an attribute in the model. In the migration:

add_column :admin, :boolean, :default => false

You can then ensure that the value is set on save:

before_save :default_admin
def default_admin
   self.admin ||= false
end