Skip to content

Instantly share code, notes, and snippets.

@kaikuchn
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaikuchn/2f5f355929b883e6adc2 to your computer and use it in GitHub Desktop.
Save kaikuchn/2f5f355929b883e6adc2 to your computer and use it in GitHub Desktop.
Single Association Replace Behavior
class Arm < ActiveRecord::Base
belongs_to :bandit, inverse_of: :arm
# instead of validating this here, you could also add a uniqueness
# constraint through a migration. Behavior would be similiar.
validates :bandit, uniqueness: true
end
class Bandit < ActiveRecord::Base
has_one :arm, dependent: :destroy, inverse_of: :bandit
end
require 'test_helper'
class BanditTest < ActiveSupport::TestCase
def setup
@bandit = Bandit.create
end
test 'grow an arm' do
assert_instance_of Arm, @bandit.create_arm!
end
test 'try to replace an arm' do
arm = @bandit.create_arm!
assert arm.persisted?
assert_raises(ActiveRecord::RecordInvalid) { @bandit.create_arm! }
# now the old arm is gone
@bandit.reload
assert_instance_of NilClass, @bandit.arm
assert_raises(ActiveRecord::RecordNotFound) { Arm.find(arm.id) }
end
end
class CreateArms < ActiveRecord::Migration
def change
create_table :arms do |t|
t.references :bandit
t.timestamps null: false
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment