From 97637dcd6bdae2087c7020aaa2027d8a210bf38e Mon Sep 17 00:00:00 2001 From: Emma Lejeck Date: Sat, 4 May 2024 16:33:27 -0700 Subject: [PATCH] Ensure bidirectional linkage in WithStory --- app/models/concerns/with_story.rb | 6 +++--- spec/models/concerns/with_story_spec.rb | 5 ++++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/app/models/concerns/with_story.rb b/app/models/concerns/with_story.rb index b7ef5aae6..17b4aacc5 100644 --- a/app/models/concerns/with_story.rb +++ b/app/models/concerns/with_story.rb @@ -7,16 +7,16 @@ module WithStory def with_story(&) belongs_to :story, optional: true, dependent: :destroy - before_update do + after_update do story_data = instance_eval(&).data story.update!(data: story_data) if story_data != story.data end - before_create do + after_create do story = instance_eval(&) story.created_at = created_at story.save! - self.story_id = story.id + update_attribute(:story_id, story.id) end end end diff --git a/spec/models/concerns/with_story_spec.rb b/spec/models/concerns/with_story_spec.rb index ea422b861..1d6005d0f 100644 --- a/spec/models/concerns/with_story_spec.rb +++ b/spec/models/concerns/with_story_spec.rb @@ -23,7 +23,10 @@ end it 'creates a story when the record is created' do - expect { StoryOwner.create! }.to change(Story, :count).by(1) + owner = StoryOwner.new + expect { owner.save! }.to change(Story, :count).by(1) + expect(Story.last.data['test_id']).to eq(owner.id) + expect(owner.story_id).to eq(Story.last.id) end it 'updates the story when the data changes' do