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.
I agree with you that what you describe should work, but if you’re building associated records in memory and expecting them to save together properly — with everything hooked up — then ActiveRecord is particularly finicky about how you define them.
But you can make it work without changing a thing in your
before_create.The usual problem is that you need to give AR hints about which relationships are inverses of each other. The
has_manyandbelongs_tomethods take an:inverse_ofoption. The problem in your case is that you have one side of a relationship (Stash#owner) that is actually the inverse of two on the other (User#stashesandUser#default_stash), so what would you set as theinverse_offorStash#owner?The solution is to add a
has_oneto Stash (call it something likeowner_as_default), to balance things out. Then you can addinverse_ofto all of the definitions, each identifying its inverse on the other side. The end result is this:(Also, you don’t need a foreign key on your belongs_to.)
From there, your
before_createshould work as you’ve written it.Yes, it seems that this is a lot of redundant defining. Can’t ActiveRecord figure it all out from the foreign keys and whatnot? I always feel like I’m breaking some walls by making one side so aware of what it’s the inverse of. Maybe in some future version of Rails this will be ironed out.