I have 2 models, User
and Stash
.
A User has many stashes, and a default_stash. A Stash has one owner (User).
Before a User is created I want it to build a Stash AND assign that Stash to self.default_stash. As per the instructions here Rails - Best-Practice: How to create dependent has_one relations I created the Stash relation, however I cannot 'create' the belongs_to relation at the same time.
User.rb
has_many :stashes, foreign_key: :owner_id
belongs_to :default_stash, class_name: 'Stash', foreign_key: :owner_id
before_create :build_default_stash
def build_default_stash
self.default_stash = stashes.build
true
end
Stash.rb
belongs_to :owner, class_name: 'User'
At this point the Stash can be found in user.stashes
but user.default_stash
remains nil, as stashes.build
does not return an id in the before_create block.
What I need can be achieved by adding the following to User.rb
after_create :force_assign_default_stash
def force_assign_default_stash
update_attribute(:default_stash, stashes.first)
end
But I'd much prefer to keep everything within the before_create
block if possible, for validations etc.