ruby-on-rails – 如何在mongoid / rails中收集一个字段?
发布时间:2020-12-17 03:48:27 所属栏目:百科 来源:网络整理
导读:我有一个模特 class MyClass include Mongoid::Document include Mongoid::Timestamps field :a,type: String field :b,type: String field :c,type: Stringend 那么如何将所有a-s,b-s或c-s作为列表/数组从MyClass集合中的所有对象中获取? Rails / Ruby / M
我有一个模特
class MyClass include Mongoid::Document include Mongoid::Timestamps field :a,type: String field :b,type: String field :c,type: String end 那么如何将所有a-s,b-s或c-s作为列表/数组从MyClass集合中的所有对象中获取? Rails / Ruby / Mongoid有没有任何语法糖? 我知道,有可能这样做: all_a = [] MyClass.desc(:created_at).each do |my_object| all_a.push(my_object.a) end 但我想到了: MyClass.get(:fields => :a) MyClass.get(:fields => :a,:b) 更新: 我发现了一些东西 MyClass.create(a: "my_a_string") MyClass.create(a: "my_another_a_string") 现在: MyClass.only(:a) 应该工作,但我得到: => #<Mongoid::Criteria selector: {} options: {:fields=>{"a"=>1}} class: MyClass embedded: false> 当MyClass.only(:a).to_a => [#<MyClass _id: 525f3b9e766465194b000000,created_at: nil,updated_at: nil,a: "my_a_string",b: nil,c: nil>,#<MyClass _id: 525f4111766465194b180000,a: "my_another_a_string",c: nil>] 但我想到了: ["my_a_string","my_another_a_string"] 要么 [{a: "my_a_string"},{a: "my_another_a_string"}] 解决方法
MyClass.only(:a),将每个其他字段返回为nil,并将所选字段及其值返回…
您可以使用MyClass.pluck(:a)代替. 如果您想要多个字段,可以执行以下操作: MyClass.only(:a,:b).map {|obj| [obj.a,obj.b]} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |