Joy
Joy

Reputation: 4473

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. I am new to Ruby on Rails and 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.

Upvotes: 2

Views: 1214

Answers (4)

derekyau
derekyau

Reputation: 2946

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.

If what you want is not an ActiveRecord relation, but rather just the ids, go with the simple "pluck" method

Student.pluck(:id)

Upvotes: 1

KappaNossi
KappaNossi

Reputation: 2716

If you really need all the student objects, use students.map(&:id) which is short for students.map{|s| s.id} and returns an array of all ids.

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.

Edit: Sorry, the pluck method is ActiveRecord only. But the other answers have an alternative with the fields option.

Upvotes: 1

user2503775
user2503775

Reputation: 4367

You need fields

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

See more : How to fetch only specified fields of model with DataMapper?

Upvotes: 0

Yehuda Zargarov
Yehuda Zargarov

Reputation: 277

Variable "students" is an array, you should not apply get_ids on it. The function should get no parameters.

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

Upvotes: 2

Related Questions