所以我有这个数据结构:
+[#<Folder id: 1, name: "mollitia", parent_id: nil, user_id: 1, created_at: "2014-06-27 16:00:59", updated_at: "2014-06-27 16:00:59">,
+ #<Folder id: 2, name: "porro", parent_id: 1, user_id: 1, created_at: "2014-06-27 16:00:59", updated_at: "2014-06-27 16:00:59">,
+ #<Folder id: 3, name: "omnis", parent_id: 2, user_id: 1, created_at: "2014-06-27 16:00:59", updated_at: "2014-06-27 16:00:59">]
由self.ancestors
返回
我能说出它的名字吗?
def pwd
self.ancestors.pluck(:name)
end
以上结果
undefined method `pluck' for #<Array:0x007ff4da780290>
更新
令人敬畏的结构打印:
[
[0] #<Folder:0x007fd2946a5f18> {
:id => 3,
:name => "blanditiis",
:parent_id => 2,
:user_id => 1,
:created_at => Fri, 27 Jun 2014 18:04:02 UTC +00:00,
:updated_at => Fri, 27 Jun 2014 18:04:02 UTC +00:00
},
[1] #<Folder:0x007fd2946ad1c8> {
:id => 2,
:name => "neque",
:parent_id => 1,
:user_id => 1,
:created_at => Fri, 27 Jun 2014 18:04:02 UTC +00:00,
:updated_at => Fri, 27 Jun 2014 18:04:02 UTC +00:00
},
[2] #<Folder:0x007fd2946b80c8> {
:id => 1,
:name => "ut",
:parent_id => nil,
:user_id => 1,
:created_at => Fri, 27 Jun 2014 18:04:02 UTC +00:00,
:updated_at => Fri, 27 Jun 2014 18:04:02 UTC +00:00
}
]
答案 0 :(得分:18)
pluck
与rails一起用于更改与数据库的关联查询。它会将其从SELECT *
更改为SELECT [attr]
,其中[attr]
是要采摘的参数。因为它是一个数组,所以你不能使用它。您应该使用ruby中的常规旧map
。在您的情况下,它看起来像:
def pwd
self.ancestors.map(&:name)
end
答案 1 :(得分:0)
pluck
已添加到Rails 5的Enumerable中,因此确实过时了https://github.com/rails/rails/issues/20339
但是,我认为最好的做法是将返回的Array
更改为ActiveRecord关系