This question appears to be the most voted/relevant question on Stack Overflow about setting default values on models. Despite the numerous ways explored, none of them cover this issue.
Note that this is an API - so the default text for a reminder must be provided by the api, hence why I am storing in the database. Some users will wish to use that default, some will update it.
Here is my code that works, but it feels wrong, because I have had to set one of the default values (for :body
) in the 'parent' (User
model).
class User < ActiveRecord::Base
# Relationships
belongs_to :account
has_one :reminder
before_create :build_default_reminder
private
def build_default_reminder
build_reminder(body: get_default_body)
end
def get_default_body
<<~HEREDOC
This is a quick reminder about the outstanding items still on your checklist.
Thank you,
#{self.name}
HEREDOC
end
end
class Reminder < ApplicationRecord
# Relationships
belongs_to :user
# Default attributes
attribute :is_follow_up, :boolean, default: true
attribute :subject, :string, default: "your checklist reminder!"
attribute :greeting, :string, default: "Hi"
end
What I would much rather do is this, so that all defaults are in the same model (the child):
class User < ActiveRecord::Base
# Relationships
belongs_to :account
has_one :reminder
end
class Reminder < ApplicationRecord
# Relationships
belongs_to :user
# Default attributes
attribute :is_follow_up, :boolean, default: true
attribute :subject, :string, default: "your checklist reminder!"
attribute :greeting, :string, default: "Hi"
attribute :body, :string, default:
<<~HEREDOC
This is a quick reminder about the outstanding items still on your checklist.
Thank you,
#{self.user.name}
HEREDOC
end
but this of course throws the error:
undefined method `user' for #<Class:0x007fa59d4d0f90>
The problem comes about because the default :body
string must contain the name of the user. Is there a way to achieve this - ie. have all the defaults in reminder
model, but somehow reference the user that created it?