ruby-on-rails – Ruby on Rails下拉框的静态列表选项

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Ruby on Rails下拉框的静态列表选项前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的数据库中有一个Person表,我有一个名为person_type的列.我不想要一个person_type的数据库模型,因为它将永远是“志愿者”或“参与者”.我将在哪里创建一个静态数组来保存这些值,以及如何将该数组绑定到Ruby on Rails select helper?最好只是创建一个选择帮手?

谢谢!

解决方法

实现这一点的最简单的方法是在你的Person模型中有一个常数:
class Person < ActiveRecord:Base
  PERSON_TYPES = ["Volunteer","Participant"]
end

然后您可以使用select帮助程序访问它们:

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

如果您需要考虑i18n,只需要稍微修改一下.

给出您的i18n文件中的这些条目:

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

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

您可以更新您的模型并查看:

# 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:

<!-- 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>
原文链接:https://www.f2er.com/ruby/273680.html

猜你在找的Ruby相关文章