是否可以创建
collection_select
或
select tag
表示
t.string
用户可以在字符串的预定义值中进行选择,只有那些允许存储在字符串数据库中的值?例如
t.string :relationship_status
我想要预定义的值:
In a relationship
Single
Maried
Engaged
ETC
答案 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>