Rails - collection_select - populate with the valu

2019-08-10 18:07发布

问题:

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}%>