MongoDB
 sql >> Teknologi Basis Data >  >> NoSQL >> MongoDB

Daftar atribut dinamis dalam Model Mongoid

Cukup sertakan sesuatu seperti ini dalam model Anda:

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

dan berikut adalah spesifikasinya:

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


  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Setara dengan mongo shell db.collection.runCommand() di Node.js

  2. Kunci asing di mongo?

  3. aplikasi nodejs - koneksi mongodb gagal dengan kesalahan ECONNREFUSED

  4. Pengecualian Waktu Habis Kurs Mongo

  5. Bagaimana cara memperbarui sebagian objek di MongoDB sehingga objek baru akan overlay/bergabung dengan yang sudah ada