【问题标题】:Select amongst predefined values for a t.string在 t.string 的预定义值中进行选择
【发布时间】:2011-07-09 14:56:14
【问题描述】:

是否可以创建一个

collection_select 

select tag 

为了一个

t.string

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

t.string :relationship_status

我想要预定义的值:

In a relationship
Single
Maried
Engaged
ETC 

【问题讨论】:

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


    【解决方案1】:

    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>
    

    【讨论】:

    • 我得到 ActionView::Template::Error(参数数量错误(3 对 4)):
    • 在您的情况下,您想要的值与id相同,因此您可以使用to_s
    • ActionView::Template::Error (undefined method permission' for #<0x00000005620408>
    猜你喜欢
    • 2015-06-08
    • 2021-11-25
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    相关资源
    最近更新 更多