Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only set/save the inverse on a HABTM if the inverse is also HABTM #757

Merged
merged 1 commit into from
Apr 7, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,16 @@ def insert_record(record, force = true, validate = true)
owner[reflection.foreign_key] ||= []
owner[reflection.foreign_key] += [record.id]

if @owner.new_record? and @reflection.options[:inverse_of]
ActiveFedora::Base.logger.warn("has_and_belongs_to_many #{@reflection.inspect} is cowardly refusing to insert the inverse relationship into #{record}, because #{@owner} is not persisted yet.") if ActiveFedora::Base.logger
elsif @reflection.options[:inverse_of]
inverse = @reflection.inverse_of
record[inverse.foreign_key] ||= []
record[inverse.foreign_key] += [owner.id]
record.save
# Only if they've explicitly stated the inverse in the options
if reflection.options[:inverse_of]
inverse = reflection.inverse_of
if owner.new_record?
ActiveFedora::Base.logger.warn("has_and_belongs_to_many #{reflection.inspect} is cowardly refusing to insert the inverse relationship into #{record}, because #{owner} is not persisted yet.") if ActiveFedora::Base.logger
elsif inverse.has_and_belongs_to_many?
record[inverse.foreign_key] ||= []
record[inverse.foreign_key] += [owner.id]
record.save
end
end

return true
Expand Down
17 changes: 17 additions & 0 deletions spec/integration/has_and_belongs_to_many_associations_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,23 @@ class Component < ActiveFedora::Base
expect(component.item_ids).to eq [item.id]
end
end

context "when the has_and_belongs_to_many provides an inverse_of" do
let(:reflection) { Component.reflect_on_association(:items) }
before do
reflection.options[:inverse_of] = :components
end

describe "shifting" do
let(:component) { Component.create }
let(:item) { Item.new }

it "should set item_ids" do
component.items << item
expect(component.item_ids).to eq [item.id]
end
end
end
end

describe "From the has_many side" do
Expand Down