下拉框的 Ruby on Rails 静态列表选项 [英] Ruby on Rails Static List Options for Drop Down Box
问题描述
我的数据库中有一个 Person 表,并且有一个名为 person_type 的列.我不想要 person_type 的数据库模型,因为它总是志愿者"或参与者".我将在哪里创建一个静态数组来保存这些值,以及如何将该数组绑定到 Ruby on Rails 选择助手?最好只创建一个选择助手吗?
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?
谢谢!
推荐答案
最简单的实现方法是在你的 Person 模型中添加一个常量:
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)
如果需要考虑i18n,只需要稍作修改即可.
If you need to consider i18n, it only needs a few slight modifications.
鉴于您的 i18n 文件中的这些条目:
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] } %>
这将为您提供所需的 HTML:
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>
这篇关于下拉框的 Ruby on Rails 静态列表选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!