是否可以创建一个
collection_select
或
select tag
对于一个
t.string
用户可以在哪里选择字符串的预定义值,并且只允许将那些值存储在字符串的数据库中?例如
t.string :relationship_status
我想要预定义值:
In a relationship
Single
Maried
Engaged
ETC
最佳答案
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
然后,在 View 中:
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>
关于ruby-on-rails - 在 t.string 的预定义值中进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6635495/