Field aliasing/labelling

929 views
Skip to first unread message

Nick Hoffman

unread,
Feb 3, 2011, 1:11:34 PM2/3/11
to mon...@googlegroups.com
Hi guys. I just noticed some strange behaviour with field aliasing RC7.

class Person
  include Mongoid::Document
  field :name, :label => :n
end

ruby-1.9.2-p0 >   Person.create :name => 'bob'
 => #<Person _id: 4d4aef488533c58f39000001, name: "bob">
ruby-1.9.2-p0 >
ruby-1.9.2-p0 >   Person.create :n => 'joe'
 => #<Person _id: 4d4aef4f8533c58f39000002, name: nil, n: "joe">

For the second Person that's created, I expected the "name" field to be set to "joe", and didn't expect the "n" field to exist.

When I look in MongoDB, the alias/label wasn't used for the first person:

> db.people.find()
{ "_id" : ObjectId("4d4aef488533c58f39000001"), "name" : "bob" }
{ "_id" : ObjectId("4d4aef4f8533c58f39000002"), "n" : "joe" }
>

Am I using field aliasing/labelling incorrectly?

Thanks for your help,
Nick

Kieran P

unread,
Feb 3, 2011, 2:49:13 PM2/3/11
to mon...@googlegroups.com
I believe :label should be :as

field :name, :as => :n

As for how "n: Joe" worked, Mongoid has dynamic fields enabled.

http://mongoid.org/docs/installation/  (see allow_dynamic_fields configuration option)

Regards
Kieran

Nick Hoffman

unread,
Feb 3, 2011, 2:57:56 PM2/3/11
to mon...@googlegroups.com

That's what I thought. However, "name" is being set in MongoDB instead of "n":

class Person
include Mongoid::Document

field :name, :as => :n
end

ruby-1.9.2-p0 > Person.create :name => 'nick'
=> #<Person _id: 4d4b07488533c594f5000001, name: "nick">
ruby-1.9.2-p0 >
ruby-1.9.2-p0 > Person.create :n => 'alex'
=> #<Person _id: 4d4b07518533c594f5000002, name: "alex">
ruby-1.9.2-p0 >

> db.people.find()
{ "_id" : ObjectId("4d4b07488533c594f5000001"), "name" : "nick" }
{ "_id" : ObjectId("4d4b07518533c594f5000002"), "name" : "alex" }
>

Unless....the value specified for :as is meant to be the human-friendly alias!

Kieran P

unread,
Feb 3, 2011, 11:06:06 PM2/3/11
to mon...@googlegroups.com
Yup, so in your case, you probably want:

field :n, :as => :name

Then both ways of assigning it should work.

Nick Hoffman

unread,
Feb 4, 2011, 9:32:52 AM2/4/11
to mon...@googlegroups.com

Thanks, mate. I got it all working.

Reply all
Reply to author
Forward
0 new messages