为t.string选择预定义的值 [英] Select amongst predefined values for a t.string

查看:117
本文介绍了为t.string选择预定义的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个

  collection_select 

 选择标记





$ p $ t.string

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

  t.string:relationship_status 

我想要预定义的值:

 在关系
Single
Maried
Engaged
ETC


解决方案

可能有用的最简单的事情 与:

  class Person< ActiveRecord :: Base 
RELATIONSHIP_STATUSES = [
single,
in relationship,
together,
很复杂
]

验证:relationship_status,:inclusion => RELATIONSHIP_STATUSES
end

然后,在视图中:

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

这产生:

 < select name =person [relationship_status]> ; 
< option value =single>单一< / option>
< / option>关系中的选项值=>>

...
< / select>


Is it possible to create a

collection_select 

or

select tag 

for a

t.string

Where a user can select amongst predefined values for the string and only those values allowed to be stored in the database for the string? For example

t.string :relationship_status

And I want predefined values:

In a relationship
Single
Maried
Engaged
ETC 

解决方案

The Simplest Thing That Could Possibly Work is along the lines of:

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

  validates :relationship_status, :inclusion => RELATIONSHIP_STATUSES
end

Then later, in the view:

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

This produces:

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

  ...
</select>

这篇关于为t.string选择预定义的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆