0

Can .pluck be used to get say only the first 5 values

e.g.

 CategoryItemKey.where(category_id: @category.id).pluck(:name)

I only want the first 5 names. Also if there are only 3 names it wont throw an error it will just grab 3.

Cant see it in the docs or from a google search. How would I accomplish this?

Rob
  • 1,835
  • 2
  • 25
  • 53

1 Answers1

1

CategoryItemKey.where(category_id: @category.id).pluck(:name)[0...5]

  • Wow it was so simple haha – Rob Mar 01 '16 at 04:16
  • 1
    You should possibly also include a `.limit(5)` in your query. In case CategoryItemKey is a large table, this would fetch all entries and then discard all except the first five, leading to some overhead. – panmari Mar 01 '16 at 06:38
  • @panmari can I just replace [0...5] with `.limit(5)`? Saving on overhead is the only reason i'm doing it. – Rob Mar 01 '16 at 07:27
  • You can leave it if you need 5 entries, even if there are less available. – panmari Mar 01 '16 at 07:41