Reputation: 14352
Given the following ActiveRecord model with an enum
column:
class User < ActiveRecord::Base
enum role: [:normal, :sales, :admin]
end
How do I set the default value for the role
column before saving to the database.
For example:
user = User.new
puts user.role # Should print 'normal'
Upvotes: 2
Views: 2795
Reputation: 6311
You can set it as :default to 'normal' in a migration file.
little good examples: LINK
class User < ActiveRecord::Base
enum role: [:normal, :sales, :admin]
#before_save {self.role ||= 'normal'}
# or
#before_create {self.role = 'normal'}
end
Upvotes: 2
Reputation: 1369
class User < ActiveRecord::Base
enum role: [:normal, :sales, :admin]
after_initialize do
if self.new_record?
self.role ||= :normal
end
end
end
or if you prefer
class User < ActiveRecord::Base
enum role: [:normal, :sales, :admin]
after_initialize :set_defaults
private
def set_defaults
if self.new_record?
self.role ||= :normal
end
end
end
Note that we use ||= to prevent the after_initialize clobbering anything passed in during initialization with User.new(some_params)
Upvotes: 7
Reputation: 185
You can use this callback, before_save
class User < ActiveRecord::Base
before_save :default_values
def default_values
self.role ||= "normal"
end
end
Upvotes: 1