加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 列出Mongoid模型中的动态属性

发布时间:2020-12-17 04:00:15 所属栏目:百科 来源:网络整理
导读:我已经阅读了文档,我找不到具体的方法来解决这个问题.我已经为模型添加了一些动态属性,我希望能够遍历所有这些属性. 所以,举一个具体的例子: class Order include Mongoid::Document field :status,type: String,default: "pending"end 然后我做以下事情:
我已经阅读了文档,我找不到具体的方法来解决这个问题.我已经为模型添加了一些动态属性,我希望能够遍历所有这些属性.

所以,举一个具体的例子:

class Order
  include Mongoid::Document

  field :status,type: String,default: "pending"
end

然后我做以下事情:

Order.new(status: "processed",internal_id: "1111")

后来我想回来并且能够获得所有动态属性的列表/数组(在这种情况下,“internal_id”就是它).

我还在挖掘,但我很想听听其他人是否已经解决了这个问题.

解决方法

只需在您的模型中包含以下内容:

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

这里有一个规范:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读