If you only need the ids and not the entire object itself, MrYoshiji's answer is best:
item_ids = Item.scoped.pluck(:id)
If, however, you already have a collection of items in @items then you can do this:
item_ids = @items.map(&:id)
Question
I have an instance variable @items
which i get from doing@items = Item.all
inside a controller action. The Item
class looks like this:
class Item < ActiveRecord::Base
attr_accessible :weight, :color, :price
validates :color, presence: true
validates :price, presence: true
end
What i would like to do is to get the values of the :id
attributes of all the items in@items
the controller action in which i'm trying to get the ids looks like this:
def get_item_ids
@items = Item.all
item_ids = ??? ## i'm stuck here
end
How can get item_ids
as an array of :id
attributes of items inside @items
?
La solution
If you only need the ids and not the entire object itself, MrYoshiji's answer is best:
item_ids = Item.scoped.pluck(:id)
If, however, you already have a collection of items in @items then you can do this:
item_ids = @items.map(&:id)