Set default value for Active Record attribute
24 April 2022 (Updated 24 April 2022)
Suppose you want to set a default attribute value for a model so that all new instances of the model have a default attribute. Something like this:
User.new.bio
=> 'Mysterious creature'
You can do this with the attribute
method:
class User < ApplicationRecord
attribute :bio, :string, default: 'Mysterious creature'
end
You can also use a lambda if you want to dynamically generate the value:
class User < ApplicationRecord
attribute :bio, :string, default: -> { Faker::Job.title }
end
Tagged:
Rails
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment