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

gla*_*kou 2 ruby forms ruby-on-rails ruby-on-rails-3

有可能创建一个

collection_select 
Run Code Online (Sandbox Code Playgroud)

要么

select tag 
Run Code Online (Sandbox Code Playgroud)

为一个

t.string
Run Code Online (Sandbox Code Playgroud)

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

t.string :relationship_status
Run Code Online (Sandbox Code Playgroud)

我想要预定义的值:

In a relationship
Single
Maried
Engaged
ETC 
Run Code Online (Sandbox Code Playgroud)

Joh*_*lla 5

可能工作最简单的事情是:

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

  validates :relationship_status, :inclusion => RELATIONSHIP_STATUSES
end
Run Code Online (Sandbox Code Playgroud)

然后,在视图中:

collection_select(:person, :relationship_status, Person::RELATIONSHIP_STATUSES, :to_s)
Run Code Online (Sandbox Code Playgroud)

这会产生:

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

  ...
</select>
Run Code Online (Sandbox Code Playgroud)