4

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?

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.