mongoid/mongoid — Issue #1461: Criteria on foreign keys fails when referenced models don't use ObjectIds 
Author: grig
Created: 2011-11-30 08:19:10+00:00
State: open

Such criteria incorrectly format query strings.

The following spec fails:

```
require 'spec_helper'

describe Mongoid::Criterion::Inclusion do
before do
[ Person, Post, Product, Game, Jar ].each(&:delete_all)
end

describe "#any_in" do
context "on foreign keys" do
context "when not using object ids" do
before(:all) do
Person.identity :type => String
end

after(:all) do
Person.identity :type => BSON::ObjectId
end

let!(:person) { Person.create }
let!(:account) { person.create_account(:name => "test") }
let(:from_db) { Account.any_in(:person_id => [ person.id ]).to_a }

it "should issue proper queries" do
from_db.should == [ account ]
end
end
end
end
end
```

Test executes the following (incorrect) query:

```
MONGODB mongoid_76988['accounts'].find({:person_id=>"{\"$in\"=>[\"4ed5e37fe269cb2cbc000002\"]}"})
```

This is a regression from v2.3.3. It was introduced by fe1472cd along with a fix for #1399. I tested it on `any_in` only, however, all criteria should fail under similar conditions.

The culprit is in lib/mongoid/fields/serializable/foreign_keys/object.rb, namely,

```
def serialize(object)
if object_id_field?
constraint.convert(object)
else
metadata.klass.fields["_id"].serialize(object)
end
end
```

When the field is not an object_id_field, this code always escapes field's value, regardless of whether it is a proper value or an operator.