I am using Ruby on Rails 3.0.7 and I would like to understand how to handle the following code in order to retrieve a class objects with a specified id
.
In my view file I have:
@records = Users.all # This returns an array (class)
In another file, a partial template, I would like to retrieve, for example, the user with id
1, but if I make this:
@records.find(1)
I get an enumerator
(class) of all records:
<Enumerator: [<Users id: 1, ... ] >
How can I find the user with id
1 (or other ids) "a là Ruby on Rails Way"?
UPDATE
I use @records = Users.all
in a view file because I aim to minimize calls to the database since I need to iterate almost over all records and check them existence. If I do for example:
some_hash.each { |key, value|
put User.find(value)
}
and I go in the log file, I will see a lot of database requests.
Even though this is probably quite slow, and I suspect there are some less than optimal designs in the app you're working on (not judging, we've all been there), Array#index seems to be what you're looking for:
@records[@records.index{|user| user.id == 1}]
Edit
Although if you need to do something for every user, and you need to access them by id quickly, I'd probably do something like this in your controller. Even if it's not really faster, it's much more readable (to me anyways):
@users_hash = {}
User.all.each{|user| @users_hash[user.id] = user}
Then in your views you can do:
@users_hash[id].username