【问题标题】:include/exclude mongoid attributes包含/排除 mongoid 属性
【发布时间】:2013-04-26 11:45:33
【问题描述】:

我有一个 mongoid 对象:

post = Post.first

当我尝试时:

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

此块解析所有对象属性。

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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2 mongoid


    【解决方案1】:
    whitelist = %w(attr attr2 attr3)
    post.attributes.select{|el| whitelist.include?(el)}.each do |key, value|
       ...
    end
    

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

    【讨论】:

    • 如果我添加whitelist = %w(post.attr post.attr2 post.attr3),我会得到一个带有["post.attr1", "post.attr2", "post.attr3"] 的数组。我想在数组里面这个属性的内容。谢谢!
    • white = ['_id']; User.first.attributes.select{|el, val| white.include?(el)} 我得到{"_id"=>BSON::ObjectId('4d5a62ac29e1676226000050')}
    • 编辑了我的答案:因为它给了你一个哈希,你必须提防do之后的args
    【解决方案2】:

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

    这也会有所帮助。

    【讨论】:

      【解决方案3】:

      您可以尝试使用仅返回指定属性的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
      

      【讨论】:

        猜你喜欢
        • 2012-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-29
        • 2016-12-13
        相关资源
        最近更新 更多