简体   繁体   中英

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!

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM