Skip to content
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
6 changes: 5 additions & 1 deletion lib/mongoid/association/constrainable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,11 @@ def convert_to_foreign_key(object)
private

def convert_polymorphic(object)
object.respond_to?(:id) ? object.id : object
if object.is_a?(Mongoid::Document)
object.id
else
BSON::ObjectId.mongoize(object)
end
end
end
end
Expand Down
58 changes: 58 additions & 0 deletions spec/mongoid/association/constrainable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,63 @@
expect(constrainable.convert_to_foreign_key("testing")).to eq("testing")
end
end

context 'when the association is polymorphic' do

let(:constrainable) do
Post.relations['posteable']
end

let(:result) do
constrainable.convert_to_foreign_key(object)
end

context 'when a BSON::ObjectId is passed' do

let(:object) do
BSON::ObjectId.new
end

it 'returns the object id' do
expect(result).to eq(object)
end
end

context 'when a string is passed' do

context 'when the string represents an ObjectId' do

let(:object) do
BSON::ObjectId.new.to_s
end

it 'returns the object id' do
expect(result).to eq(BSON::ObjectId.from_string(object))
end
end

context 'when the string does not represent an ObjectId' do

let(:object) do
'some-other-string'
end

it 'returns the object' do
expect(result).to eq(object)
end
end
end

context 'when a model object is passed' do

let(:object) do
Post.new
end

it 'returns the id' do
expect(result).to eq(object.id)
end
end
end
end
end
2 changes: 1 addition & 1 deletion spec/mongoid/fields/foreign_key_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,7 @@
end

it "does not change the foreign key" do
expect(evolved).to be(value)
expect(evolved).to eq(BSON::ObjectId.from_string(value))
end
end
end
Expand Down