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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With