在t.string的预定义值中选择

时间:2011-07-09 14:56:15

标签: ruby-on-rails ruby ruby-on-rails-3 forms

是否可以创建

collection_select 

select tag 

表示

t.string

用户可以在字符串的预定义值中进行选择,只有那些允许存储在字符串数据库中的值?例如

t.string :relationship_status

我想要预定义的值:

In a relationship
Single
Maried
Engaged
ETC 

1 个答案:

答案 0 :(得分:5)

Simplest Thing That Could Possibly Work符合以下几行:

class Person < ActiveRecord::Base
  RELATIONSHIP_STATUSES = [
    "single",
    "in a relationship",
    "together",
    "it's complicated"
  ]

  validates :relationship_status, :inclusion => RELATIONSHIP_STATUSES
end

然后,在视图中:

collection_select(:person, :relationship_status, Person::RELATIONSHIP_STATUSES, :to_s)

这会产生:

<select name="person[relationship_status]">
  <option value="single">single</option>
  <option value="in a relationship">in a relationship</option>

  ...
</select>