Forum: Ruby on Rails using one-dimensional arrays in select statements (noob)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
sean (Guest)
on 2005-12-06 22:32
I have an issue whereby I want the attributes on an object to be saved
in the db as simple integers and the corresponding labels to be stored
in the class.

DB Car:
id int, name varchar(10), speed int

Model Car:
class Car < ActiveRecord::Base
  Speed = %w{Slow Normal Fast}
end

View Car:
<select name="mycar[speed]">
<option value=0>Slow</option>
<option value=1>Normal</option>
<option value=2>Fast</option>
</select>

What is the select statement to get the options to print out like that?
Now I know that I could set Speed to be a hash (Speed = {"slow"=>0,
"normal"=>1, "fast"=>2}) but then I would lose the ordering, which is
important. I could use an associative array as well (Speed = [["Slow",
0],["Normal", 1],["Fast", 2]]) but this Car object will have a number of
similar attributes so that would seem to violate the DRY principal
having to put 0, 1, 2, etc in every time.

Is there a way to print out a select statement using a simple
one-dimensional array with the item's index value acting as the key in
the option tag?

I very much want to do this the Ruby way. Any help would be greatly
appreciated.
jeremyevans0 (Guest)
on 2005-12-07 01:49
(Received via mailing list)
On 12/6/05, sean <removed_email_address@domain.invalid> wrote:
> What is the select statement to get the options to print out like that?
> Now I know that I could set Speed to be a hash (Speed = {"slow"=>0,
> "normal"=>1, "fast"=>2}) but then I would lose the ordering, which is
> important. I could use an associative array as well (Speed = [["Slow",
> 0],["Normal", 1],["Fast", 2]]) but this Car object will have a number of
> similar attributes so that would seem to violate the DRY principal
> having to put 0, 1, 2, etc in every time.

There isn't a method that does exactly what you want, as far as I
know. But here's an idea that is pretty good with regards to DRY:

class Array
  def with_indexes
     a = []
     each_with_index {|x,i| a << [x,i]}
     a
  end
end

Model Car:
class Car < ActiveRecord::Base
 @@speeds = %w{Slow Normal Fast}
 cattr_reader :speeds
end

View Car:
select("mycar", "speed", Car.speeds.with_indexes)
sean <> (Guest)
on 2005-12-07 16:41
jeremyevans0 wrote:
>
> There isn't a method that does exactly what you want, as far as I
> know. But here's an idea that is pretty good with regards to DRY:
>

That is an excellent solution, thanks very much for your input on what
was a vexing issue.
This topic is locked and can not be replied to.