0

我有一个 mongoid 对象:

post = Post.first

当我尝试:

post.attributes.each do |a|
...
end

此块解析所有对象属性。

我只需要解析 3 个属性。post.attr1, post.attr2, post.attr3.

4

3 回答 3

1
whitelist = %w(attr attr2 attr3)
post.attributes.select{|el| whitelist.include?(el)}.each do |key, value|
   ...
end

像往常一样,试着抽象一下。

于 2013-04-26T11:49:40.583 回答
0

您可以尝试使用only仅返回指定属性的方法(它还添加"_id"字段),例如:

post = Post.only(:attr_1,:attr_2).first # This will give you something like => {"_id"=>"50cf2e893428ed5437000002", "attr_1"=>value, "attr_2"=>2012-12-21 02:00:00 UTC} 

post.attributes.each do |a|
  next if a.first == "_id" # each `a` is an array, for instance: ["_id", "50cf2e893428ed5437000002"]
  #do something with the attributes
end
于 2013-04-26T12:34:38.430 回答
0

post.attributes.except("id", "created_at", "updated_at").each do |attr| .... end

这也会有所帮助。

于 2013-04-26T11:51:13.613 回答