Chr*_*ber 4 ruby dynamic mongodb mongoid
我已经阅读了文档,我找不到具体的方法来解决这个问题.我已经为模型添加了一些动态属性,我希望能够遍历所有这些属性.
所以,举一个具体的例子:
class Order
include Mongoid::Document
field :status, type: String, default: "pending"
end
Run Code Online (Sandbox Code Playgroud)
然后我做以下事情:
Order.new(status: "processed", internal_id: "1111")
Run Code Online (Sandbox Code Playgroud)
后来我想回来并且能够获得所有动态属性的列表/数组(在这种情况下,"internal_id"就是它).
我还在挖,但我很想知道是否有其他人已经解决了这个问题.
这将只给出给定记录x的动态字段名称:
dynamic_attribute_names = x.attributes.keys - x.fields.keys
Run Code Online (Sandbox Code Playgroud)
如果使用其他Mongoid功能,则需要减去与这些功能关联的字段:例如Mongoid::Versioning:
dynamic_attribute_names = (x.attributes.keys - x.fields.keys) - ['versions']
Run Code Online (Sandbox Code Playgroud)
仅获取动态属性的键/值对:
确保克隆属性()的结果,否则你修改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)}
Run Code Online (Sandbox Code Playgroud)
或者在一行中:
x.attributes.clone.delete_if{|k,v| ! dynamic_attribute_names.include?(k)}
Run Code Online (Sandbox Code Playgroud)
小智 5
只需在您的模型中包含以下内容:
module DynamicAttributeSupport
def self.included(base)
base.send :include, InstanceMethods
end
module InstanceMethods
def dynamic_attributes
attributes.keys - _protected_attributes[:default].to_a - fields.keys
end
def static_attributes
fields.keys - dynamic_attributes
end
end
end
Run Code Online (Sandbox Code Playgroud)
这里有一个规范:
require 'spec_helper'
describe "dynamic attributes" do
class DynamicAttributeModel
include Mongoid::Document
include DynamicAttributeSupport
field :defined_field, type: String
end
it "provides dynamic_attribute helper" do
d = DynamicAttributeModel.new(age: 45, defined_field: 'George')
d.dynamic_attributes.should == ['age']
end
it "has static attributes" do
d = DynamicAttributeModel.new(foo: 'bar')
d.static_attributes.should include('defined_field')
d.static_attributes.should_not include('foo')
end
it "allows creation with dynamic attributes" do
d = DynamicAttributeModel.create(age: 99, blood_type: 'A')
d = DynamicAttributeModel.find(d.id)
d.age.should == 99
d.blood_type.should == 'A'
d.dynamic_attributes.should == ['age', 'blood_type']
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2931 次 |
| 最近记录: |