Rails - collection_select - populate with the values listed in a model

我们两清 提交于 2019-12-11 12:13:25

问题


I have a model defined like that:

class Order < ActiveRecord::Base
  belongs_to :user

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

I am trying to make a dropdown menu in the view that will be populated by values available in TYPES.

The one shown below is of course not the right one, because it populates dropdown menu with types that belong to orders already recorded in DB:

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

Can somebody give me any hint how I can sort it out? Thank you in advance.


回答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:


You can also use this as

<%= f.collection_select :order_type, Order::TYPES , :to_s, :to_s, {include_blank: false}%>



来源:https://stackoverflow.com/questions/32445865/rails-collection-select-populate-with-the-values-listed-in-a-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!