Miguel Peniche
Miguel Peniche

Reputation: 1032

Ruby / Rails: How to get an object from an array with attribute

My question is very simple, I have:

@users = User.first(100)

From the @users array, how can i get the user object with the id 50?

Upvotes: 1

Views: 2103

Answers (3)

Miguel Peniche
Miguel Peniche

Reputation: 1032

I have found a solution myself, but I'll wait until other people tell us which answer is better.

@users.find {|u| u.id == 50 }

Thanks for your answers!

Upvotes: 2

John Baker
John Baker

Reputation: 2398

If you want to do an ActiveRecord find you can do:

@users = User.find_by_id(50)

Or if you want to do an Array find you can do:

@users.find_all { |user| user.id == 50 }

Upvotes: 2

Jagdeep Singh
Jagdeep Singh

Reputation: 4920

Use detect:

user = @users.detect { |u| u.id == 50 }

Though there are ways to fetch just one record (with id 50) if you don't need the remaining 99.

Upvotes: 3

Related Questions