如何获取模型的所有属性减去一些属性

问题描述 投票:0回答:4

所以我正在编写一个 rspec 测试。它将测试模型是否正确复制。所以规格是这样的:

  it "should copy the data" do
    @model = build(:model)
    @another_model.copy_data(@model)
    @model.data.should == @another_model.data
  end

数据是嵌入文档,因此当我执行此操作时它会重复。模型上的所有属性都已成功复制,减去 id 和created_at 日期。我有办法做这样的事情吗?

    @model.data.attributes.without(:_id, :created_at).should == @another_model.data.attributes.without(:_id, :created_at)

或者反过来,我选择没有 id 和created_at 的所有其他字段?

谢谢!

ruby-on-rails rspec mongoid
4个回答
42
投票

这有效

@model.attributes.except("id", "created_at").should == @another_model.attributes.except("id", "created_at")

0
投票

您可以执行类似的操作,因为

.attributes
返回一个哈希,其中每个键值对都是一个属性及其值。

@model.data.attributes.each do |k,v|
  next if k == 'id' || k == 'created_at' # Skip if the key is id or created_at
  v.should == @another_model.data.attributes[k]
end

0
投票

model.attribute_names.reject { |att| att if %w(idcreated_atupdated_at).include?注意}

这对我有用


0
投票

聚会迟到了,但没有人建议:

@model.attributes - %w(id, created_at)

看起来很干净。

© www.soinside.com 2019 - 2024. All rights reserved.