Find a record in a find array

534 views
Skip to first unread message

Paul Bergstrom

unread,
Sep 16, 2011, 5:01:16 PM9/16/11
to rubyonra...@googlegroups.com
A find will make an array, right? Or is it a hash? Anyway, if I have
several records in an array/hash, how can I find e.g. record with id 10
and it's content?

--
Posted via http://www.ruby-forum.com/.

Tim Shaffer

unread,
Sep 16, 2011, 5:35:17 PM9/16/11
to rubyonra...@googlegroups.com
I'm not quite sure what you're getting at here.

If you have a model named Post, you could easily find the record with ID of 10 by doing the following:

Post.find(10)

But if you truly do have an array of post instances, you can find the one with ID of 10 using Enumerable.find:

array_name.find { |instance| instance.id == 10 }

Colin Law

unread,
Sep 17, 2011, 5:34:56 AM9/17/11
to rubyonra...@googlegroups.com
On 16 September 2011 22:01, Paul Bergstrom <li...@ruby-forum.com> wrote:
> A find will make an array, right? Or is it a hash? Anyway, if I have
> several records in an array/hash, how can I find e.g. record with id 10
> and it's content?

If you already have the results of a find operation, @records for
example (which is like an array with extra functionality) then to find
the record with id 10 within that by
@record10 = @records.find(10)

Similarly you can do other active record find operations involving
conditions, order and so on.

Or of course you can simply do Record.find(10) to get the original
record from the db as Tim has pointed out.

Colin

--
gplus.to/clanlaw

Reply all
Reply to author
Forward
0 new messages