Reputation: 8434
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.
Upvotes: 2
Views: 1962
Reputation: 1796
A more correct answer is:
# models/user.rb
before_create :default_admin
def default_admin
self.admin ||= false
end
because is only on create
and no in uptade
like before_save
Upvotes: 4
Reputation: 96
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
Upvotes: 3