Field aliases with Mongoid and Rails

风格不统一 提交于 2020-01-21 03:16:13

问题


It's common practice in MongoDB to use short key names to save space. For example, one might want to use "fn" instead of "first_name"

However in your app, you're screwed if you use "fn" all over the place. It's too ugly. For Rails specifically, is there an easy way to specify an alias when declaring a field in Mongoid?

Also, does anyone know of any open source sample projects that use Mongoid?

Thanks!


回答1:


you should consider using

 field :fn, :as => :firstname

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

this is a very good practice which is fully supported in mongoid.




回答2:


I've never seen short key names in any MongoDB projects, so I wouldn't say it's common practice. I don't think you'd see a noticeable speed improvement and it would complicate your code unnecessarily. Descriptive names are good so long they aren't so descriptive that it takes you forever to type.

There's lots of MongoDB open-source projects. Just do a search on github.

-- edit below --

This was a pretty opinionated answer. Overwriting the processing methods (https://github.com/mongoid/mongoid/blob/master/lib/mongoid/attributes/processing.rb) as described in other answers is more appropriate in the scenario where you MUST have small field names.




回答3:


Something like this should work in your class file. (It hasn't been tested in all cases, just passing a hash into create or update.)

  field :fn, :type => String

  alias :first_name :fn
  alias :filtered_process :process

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


来源:https://stackoverflow.com/questions/4227205/field-aliases-with-mongoid-and-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!