Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails Static List Options for Drop Down Box

I have a Person table in my database and I have a column named person_type. I don't want a database model for person_type as it will always be either "Volunteer" or "Participant". Where would I create a static array to hold these values and how would I bind that array to the Ruby on Rails select helper? Would it be best to just create a select helper?

Thanks!

like image 725
Mike Avatar asked Feb 22 '11 01:02

Mike


1 Answers

The simplest way to implement this is by having a constant in your Person model:

class Person < ActiveRecord:Base
  PERSON_TYPES = ["Volunteer", "Participant"]
end

which you can then access using the select helper:

f.select(:person_type, Person::PERSON_TYPES)

If you need to consider i18n, it only needs a few slight modifications.

Given these entries in your i18n files:

# config/locales/en.yml
person_types:
  volunteer: "Volunteer"
  participant: "Participant"

# config/locales/de.yml
person_types:
  volunteer: "Freiwillige"
  participant: "Teilnehmer"

You can update your model and view thus:

# app/models/person.rb
class Person < ActiveRecord:Base
  # The values have been made lower-case to match the conventions of Rails I18n
  PERSON_TYPES = ["volunteer", "participant"]
end

# app/views/people/_form.html.erb
<%= f.select :person_type, Person::PERSON_TYPES.map { |s| [I18n.t("person_types.#{s}"), s] } %>

This will give you the HTML you're after:

<!-- assuming the current I18n language is set to 'de' -->
<select name="person[person_type]">
  <option value="volunteer">Freiwillige</option>
  <option value="participant">Teilnehmer</option>
</select>
like image 181
dnch Avatar answered Nov 14 '22 14:11

dnch