Keenan Thompson
Keenan Thompson

Reputation: 980

Make an array of id's of a model in Rails

My question is simple... or so it seems. If @set.cards retrieves "id", "front", "back", "created_at" (etc.). How do I get just an array of the id's? [1,2,3,4,5...etc]?

Upvotes: 1

Views: 1609

Answers (2)

Harish Shetty
Harish Shetty

Reputation: 64363

Rails provides a standard method for this:

@set.card_ids

Reference: The has_many documentation. Look at the 5th method from the top, i.e. collection_singular_ids.

Upvotes: 5

Frank
Frank

Reputation: 1081

This will work:

@set.cards.map(&:id)

Upvotes: 4

Related Questions