Find a record in existing resultset
My setup: Rails 3.0.9, Ruby 1.9.2
Let's say I did a find all on a model
@projects = Project.all
Now I would like find an individual record with开发者_如何学运维in the resultset just returned without having to make it another SQL call. This line of code triggers a new SQL call, I'll like to avoid it if possible, figures there should be a way to grab the record from the resultset
@projects.find(1)
@projects
is just an array of Project objects now you can simply use any ruby operator that operates on arrays to find the object you want.
For example:
@projects.first {|item| item.id == 1}
is the same as your example.
You could also use something like:
@projects.select {|item| item.foo == 3}
if you knew you could match multiple items.
I prefer @projects.detect { |item| item.foo == 3 }
over @projects.select { |item| item.foo == 3 }.first
, because it stops the iteration upon finding the first match.
精彩评论