Skip to content

Instantly share code, notes, and snippets.

@betesh
Last active September 18, 2022 04:15
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save betesh/dd97a331f67736d8b83a to your computer and use it in GitHub Desktop.
Save betesh/dd97a331f67736d8b83a to your computer and use it in GitHub Desktop.
how to append a has_many association without hitting the database immediately
source 'https://rubygems.org'
gem 'activerecord', '~> 3.2.18'
gem 'sqlite3', '= 1.3.5'
gem 'rspec'
require "active_record"
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ":memory:")
RSpec.configure do |config|
config.before(:suite) do
Class.new(ActiveRecord::Migration) do
def change
create_table :parents
create_table :children do |t|
t.references :parent
end
end
end.new.change
end
end
class Parent < ActiveRecord::Base
has_many :children, :inverse_of => :parent
end
class Child < ActiveRecord::Base
belongs_to :parent, :inverse_of => :children
end
describe Child do
describe "when new_record" do
let(:parent) { Parent.create! }
before(:each) { expect(parent).to be_persisted }
it "writes to database using <<" do
parent.children << subject
expect(subject).to be_persisted
expect(subject.parent_id).to eq(parent.id)
expect(parent.children).to include(subject)
end
it "does not write to database using using add_to_target" do
parent.association(:children).add_to_target(subject)
expect(subject).not_to be_persisted
expect(subject.parent_id).to be_nil
expect(parent.children).to include(subject)
parent.save!
expect(subject).to be_persisted
end
end
describe "when persisted" do
let(:parent) { Parent.create! }
subject { described_class.create! }
before(:each) { expect(parent).to be_persisted }
before(:each) { expect(subject).to be_persisted }
it "writes to database using <<" do
parent.children << subject
expect(subject).to be_persisted
expect(subject.parent_id).to eq(parent.id)
expect(parent.children).to include(subject)
end
it "does not write to database using using add_to_target" do
parent.association(:children).add_to_target(subject)
expect(subject).to be_persisted # Since it already was persisted
expect(subject.parent_id).to be_nil # This is less than ideal but will have to do
expect(parent.children).to include(subject)
parent.save!
expect(subject).to be_persisted
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment