Dynamic attributes with Rails and Mongoid

杀马特。学长 韩版系。学妹 提交于 2019-11-28 17:38:12

Mongoid doesn't really support it.

I happen to have asked this at Mongoid group myself.

It is possible when you create new document, like this:

account = Account.new(:some_dynamic_field => "...")

Ben Zittlau

Mongoid now supports Dynamic Fields. Their documentation can be found here: http://mongoid.org/en/mongoid/docs/documents.html#dynamic_fields

Basically it warns that you have to be slightly careful how you set dynamic fields as it will raise a no method error if you attempt to use the getter and setter methods for a field that did not exist in the document.

[],[]= are shortcuts for read_attribute(),write_attribute() , and should be used if you do not set dynamic_attributes = true in your ./config/mongoid.yml file , otherwise you'll get a no method error.

Setting allow_dynamic_fields: true can be risky, as you might pollute your data/schema with unintended fields caused by bugs in your code. It's probably safer to set this to false and explicitly use [],[]=

# Raise a NoMethodError if value isn't set.
person.gender
person.gender = "Male"

# Retrieve a dynamic field safely.
person[:gender]
person.read_attribute(:gender)

# Write a dynamic field safely.
person[:gender] = "Male"
person.write_attribute(:gender, "Male")
gucki

Be sure to set allow_dynamic_fields: true in mongoid.yml. Example:

defaults: &defaults
  allow_dynamic_fields: true
  parameterize_keys: true
  persist_in_safe_mode: true
  raise_not_found_error: true
  reconnect_time: 3
  use_object_ids: false

development:
  <<: *defaults

...
Tilo

interesting article about Dynamic Attributes with Mongoid and Rails 3.1: http://paul-wong-jr.blogspot.com/2012/03/dynamic-attributes-and-mongodbmongoid.html

To access only the dynamic key/value pairs or dynamic attribute names, see also: List dynamic attributes in a Mongoid Model

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