Reputation: 1289
I have a model Category in my Rails application that has an attribute Name. When adding an item of another model, I want the user to have the option of selecting category names from a dropdown list based on the class variable @categories.
To do this, I need to generate a string array of names from an array of type Category, but I am not quite sure how to do this without putting a string representation of the entire Category object in each dropdown item.
Does anyone know how to do this--get an array of class attributes from an array of class objects?
Upvotes: 4
Views: 5470
Reputation: 7434
You can grab an array of specific class attributes using ActiveRecord
's pluck
method.
Category.pluck(:name)
If you have a regular array of Category
objects, then you can use the Array
method map
Category.map(&:name)
Both will yield an array containing the value of the name
attribute of each Category
.
Upvotes: 10