List dynamic attributes in a Mongoid Model

后端 未结 6 1370
醉酒成梦
醉酒成梦 2021-02-06 15:49

I have gone over the documentation, and I can\'t find a specific way to go about this. I have already added some dynamic attributes to a model, and I would like to be able to it

6条回答
  •  忘了有多久
    2021-02-06 16:37

    this will give you only the dynamic field names for a given record x:

    dynamic_attribute_names = x.attributes.keys - x.fields.keys
    

    if you use additional Mongoid features, you need to subtract the fields associated with those features: e.g. for Mongoid::Versioning :

    dynamic_attribute_names = (x.attributes.keys - x.fields.keys) - ['versions']
    

    To get the key/value pairs for only the dynamic attributes:

    make sure to clone the result of attributes(), otherwise you modify x !!

    attr_hash = x.attributes.clone  #### make sure to clone this, otherwise you modify x !!
    dyn_attr_hash = attr_hash.delete_if{|k,v| ! dynamic_attribute_names.include?(k)}
    

    or in one line:

    x.attributes.clone.delete_if{|k,v| ! dynamic_attribute_names.include?(k)}
    

提交回复
热议问题