简体   繁体   English

从对象集合中提取ID

[英]Extraction of ids from a collection of objects

I have a collection of objects students. 我有一组对象的学生。 I want to get only ids of all the students. 我只想获得所有学生的身份证。 Student model is implemented in Datamapper. 学生模型在Datamapper中实现。 I am new to Ruby on Rails and Datamapper. 我是Ruby on Rails和Datamapper的新手。 Is there any way so that I can get id of all the students in collection students. 有什么办法可以让我获得集合学生中所有学生的身份证。 So basically I want the following thing: 所以基本上我想要以下东西:

 students = Student.all 
 ids = students.get_ids

I don't know how to implement get_ids. 我不知道如何实现get_ids。

Variable "students" is an array, you should not apply get_ids on it. 变量“学生”是一个数组,您不应在其上应用get_ids。 The function should get no parameters. 该函数应该没有参数。

def get_ids
  Student.all.map { |student| student.id }
end

You need fields 您需要fields

Student.all(:fields=>[:id])

See more : How to fetch only specified fields of model with DataMapper? 查看更多: 如何使用DataMapper仅获取模型的指定字段?

If you really need all the student objects, use students.map(&:id) which is short for students.map{|s| s.id} 如果你真的需要所有的学生对象,使用students.map(&:id)这是短期的students.map{|s| s.id} students.map{|s| s.id} and returns an array of all ids. students.map{|s| s.id}并返回包含所有ID的数组。

To get the ids directly from your database, use Student.where(...).pluck(:id) without all , which is much faster and less memory intensive than instantiating all the student objects. 要直接从数据库中获取ID,请使用不带all Student.where(...).pluck(:id) ,它比实例化所有Student对象要快得多,占用的内存也少。

Edit: Sorry, the pluck method is ActiveRecord only. 编辑:对不起,采摘方法是仅ActiveRecord。 But the other answers have an alternative with the fields option. 但是其他答案也可以选择使用fields选项。

If you just want to get an active record relation, try this: 如果您只想获得活动的记录关系,请尝试以下操作:

Student.select(:id)

That should return you an ActiveRecord relation with all the objects and IDs in each object. 那应该返回一个ActiveRecord关系,其中包含所有对象和每个对象中的ID。

If what you want is not an ActiveRecord relation, but rather just the ids, go with the simple "pluck" method 如果您想要的不是ActiveRecord关系,而只是ID,请使用简单的“ pluck”方法

Student.pluck(:id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM