【问题标题】:Rails - collection_select - populate with the values listed in a modelRails - collection_select - 填充模型中列出的值
【发布时间】:2015-12-03 10:25:19
【问题描述】:

我有一个这样定义的模型:

class Order < ActiveRecord::Base
  belongs_to :user

  TYPES = %w[t_01 t_02 t_03]
  validates :order_type, inclusion: { in: TYPES }
end

我正在尝试在视图中创建一个下拉菜单,该菜单将由 TYPES 中可用的值填充。

下面显示的当然不是正确的,因为它填充了属于已经记录在数据库中的订单的类型的下拉菜单:

<div class="field">
  <%= f.label :order_type %><br>
  <%= f.collection_select :order_type, Order.all, :order_type, :order_type %>
</div>

有人可以给我任何提示我如何解决它吗?先感谢您。

【问题讨论】:

    标签: ruby-on-rails collection-select


    【解决方案1】:
    #model
    
     def self.types
      TYPES
     end
    
    
     #view
     <%= f.collection_select :order_type, Order.types, :to_s, :to_s, {include_blank: false}, {:multiple => false} %>
    

    【讨论】:

    • 完美!谢谢你:)
    【解决方案2】:

    你也可以这样用

    &lt;%= f.collection_select :order_type, Order::TYPES , :to_s, :to_s, {include_blank: false}%&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2014-06-25
      • 2014-11-09
      • 2015-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多