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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With