2011-02-01 141 views
41

多重選擇,我有以下我的形式選擇框:Ruby on Rails的 - 在f.select

Related Type: &nbsp; <%= f.select(:TYPE, [['Type A', 'Type A'], 
            ['Type B', 'Type B'], 
            ['Type C', 'Type C'], 
            ['Type D', 'Type D'], 
            ['Type E', 'Type E'] 
           ],{ :prompt => "Please select"} 
           ) %> 

我想允許用戶進行多重選擇,也使選擇框的大小5.

如何爲上面的代碼做到這一點?

回答

65

在您的{ :prompt => "Please select"}之後添加另一個帶html選項的散列,例如

<%= f.select(:TYPE, [['Type A', 'Type A'], 
            ['Type B', 'Type B'], 
            ['Type C', 'Type C'], 
            ['Type D', 'Type D'], 
            ['Type E', 'Type E'] 
           ],{ :prompt => "Please select"}, 
            { :multiple => true, :size => 5 } 
           ) %> 

一旦你做到了這一點,你可能想將您的:prompt選項(保持空{}雖然使HTML屬性沒有得到治療的鐵軌選項。)

而且你需要以確保您的控制器代碼正確接受和處理多個值。

+6

爲什麼會出現這種添加「---」和「 - 」號一個儲存在每個非選擇的選項:TYPE? – 2011-12-09 13:36:38

+0

當我將它保存在表單中時,它在位置0處需要額外的空「」 「ids」=> [[0]「」, [1]「some_id」] – 2017-11-29 12:56:58

8

在收集的情況下,嘗試

<%= f.select(:TYPE, Categories.collect {|p| [ p.name, p.id ] }, 
              { :prompt => "Please select"}, 
              { :multiple => true, :size => 5 }) %> 
+1

不應該是`Category.all。 collect`? – 2017-02-14 19:26:20

0

{:提示=> 「請選擇」},{:多=>真實,:大小=> 5} {}是重要的,當f.select

6

我有一個完全工作實例(包括預選編輯對象時)中,當:

  • Object是考慮對象
  • similar_ids的關鍵是關係,是一個string

形式:

form_for(@object) do |f| 
    = f.select :similar_ids, options_from_collection_for_select(Object.all, :id, :name, {:selected => @object.similar_ids.split(';')}), {}, {:multiple => true, :size => 4, :name => 'object[similar_ids][]'} 

而在Object.rb模式:

class Object < ActiveRecord::Base 
    before_save :handle_similars 

    def handle_similars 
    self.similar_ids = self.similar_ids.select(&:present?).join(';') 
    # .select(&:present?) is necessary to avoid empty objects to be stored 
    end 

    def similars 
    self.class.find(self.similar_ids.split(';')) 
    end 

end 

這些帖子幫了我:

希望它可以幫助