开发者

Field aliasing in Mongoid

Does anyone know if Mongoid has built in support to alias field names? I've been running some tests where I have a collection with a minimal amount of fields (7 fields). If I use descriptive names and load real data and then use greatly shortened names and load the same real world data I see a 40%开发者_如何学JAVA reduction in the total size of my collection. In looking at other drivers for MongoDB (non Ruby) I see that some of them have built in support where you can write code against a descriptive name but the persistence is smart enough to use developer defined aliases. I'm just trying to determine if Mongoid has anything similar.


actually the best way to do this is NOT using ruby alias but:

field :fn, :as => :firstname

as outlined here: http://groups.google.com/group/mongoid/browse_thread/thread/ce3298d6a167bd70


Actually, the following must also be included for passing a hash to new or update_attributes:

  alias :filtered_process :process

  def process(attrs = nil)
    attrs[:fn] = attrs[:first_name] unless attrs.nil?
    filtered_process(attrs)
  end

This allows your alias to be mapped to the field on the create or update calls. It would be trivial to then track alias to field mappings in order to abstract this process.


According to this answer, you should be able to just use alias like this:

class Foo
  include Mongoid::Document

  field :fn, :type => String
  alias :first_name :fn
end

Keep in mind that this will not let you use the alias in queries and may cause some bugs. It should be fine for simple usage in instance methods and views.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜