Sebastien
Sebastien

Reputation: 6660

Get element by id from an activerecord hash with rails

I get my hash using this :

@hotels = Hotel.all

it returns : [Hotel1, Hotel2...]

How can i extract from this hash the Hotel id=10 for example?

Thank you for help.

Upvotes: 0

Views: 2887

Answers (3)

chrispanda
chrispanda

Reputation: 3224

@hotels.select{|h| h.id==10}
#=>[Hotel10]

Upvotes: 1

Jakob S
Jakob S

Reputation: 20125

To find a single element from the Array:

@hotels.find { |h| h.id == 10 }
#=> Hotel10

You might be better off doing Hotel.find(10) instead, though.

Upvotes: 2

Bohdan
Bohdan

Reputation: 8408

Try Array#select

a.select {|hotel| hotel.id == 10}

Upvotes: 0

Related Questions