Dynamic attributes with Rails and Mongoid

后端 未结 4 835
自闭症患者
自闭症患者 2020-12-13 07:28

I\'m learning MongoDB through the Mongoid Ruby gem with Rails (Rails 3 beta 3), and I\'m trying to come up with a way to create dynamic attributes on a model based on fields

4条回答
  •  囚心锁ツ
    2020-12-13 08:09

    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")
    

提交回复
热议问题