How do I create a collection

Hopefully this isn’t a dumb question.

I would like to create a drop down list using collection_select, but I
would like the collection to be generate statically, and not from a
database call.

If I do create the collection from a database table call, the output
using inspect looks like this:

[#<Carrier:0x3479338 @attributes={“name”=>“FedEx”, “enabled”=>“1”,
“id”=>“1”}>, #<Carrier:0x34792fc @attributes={“name”=>“USPS”,
“enabled”=>“1”, “id”=>“2”}>]

How do I recreate an array like this without using activerecord and a
database to do it?

To me it looks like an array of hashes, but I don’t quite understand
where the Carrier @attributes part comes from.

Any help is appreciated. Seems like something so simple, I just cant
seem to get it.


But, seriously…

Take a look at:

options_for_select(container, selected = nil)
Accepts a container (hash, array, enumerable, your type) and returns a
string of option tags. Given a container where the elements respond to
first and last (such as a two-element array), the “lasts” serve as
option values and the “firsts” as option text. Hashes are turned into
this form automatically, so the keys become “firsts” and values become
lasts. If selected is specified, the matching “last” or element will
get the selected option-tag. Selected may also be an array of values
to be selected when using a multiple select.

Examples (call, result):

As a side note you don’t necessarily need collection_select for
dealing with a static list.

Take a look a the rails documentation for:
select(object, method, choices, options = {}, html_options = {})

which will in turn direct you to the previous post for the format of

Here’s one way to create a collection:

words = %w{ this is a collection of some words }

Here’s another (This one is an empty collection):

objects = []

Now you can use the << method to add stuff to your collection:

object << my_object

On May 15, 5:02 pm, David C. [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs