Skip to content

Commit

Permalink
Ensure bidirectional linkage in WithStory
Browse files Browse the repository at this point in the history
  • Loading branch information
NuckChorris committed May 4, 2024
1 parent a23cdfa commit 97637dc
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
6 changes: 3 additions & 3 deletions app/models/concerns/with_story.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion spec/models/concerns/with_story_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 97637dc

Please sign in to comment.