Last active
August 29, 2015 14:15
-
-
Save kaikuchn/2f5f355929b883e6adc2 to your computer and use it in GitHub Desktop.
Single Association Replace Behavior
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Bandit < ActiveRecord::Base | |
has_one :arm, dependent: :destroy, inverse_of: :bandit | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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