下载框的Ruby on Rails静态列表选项

Mik*_*ike 15 ruby-on-rails ruby-on-rails-3

我的数据库中有一个Person表,我有一个名为person_type的列.我不想要person_type的数据库模型,因为它总是"志愿者"或"参与者".我将在哪里创建一个静态数组来保存这些值,以及如何将该数组绑定到Ruby on Rails select helper?是否最好只创建一个选择助手?

谢谢!

Dan*_*ail 40

实现此目的的最简单方法是在Person模型中使用常量:

class Person < ActiveRecord:Base
  PERSON_TYPES = ["Volunteer", "Participant"]
end
Run Code Online (Sandbox Code Playgroud)

然后您可以使用select helper访问它:

f.select(:person_type, Person::PERSON_TYPES)
Run Code Online (Sandbox Code Playgroud)

如果你需要考虑i18n,只需要稍加修改即可.

鉴于您的i18n文件中的这些条目:

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

# config/locales/de.yml
person_types:
  volunteer: "Freiwillige"
  participant: "Teilnehmer"
Run Code Online (Sandbox Code Playgroud)

您可以更新模型和视图:

# 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] } %>
Run Code Online (Sandbox Code Playgroud)

这将为您提供以下HTML:

<!-- 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>
Run Code Online (Sandbox Code Playgroud)