簡體   English   中英

Rails的collection_select幫助方法和最后的“創建項目”選項

[英]Rails' collection_select helper method and the “Create item” option at the end

是否可以在使用collection_select輔助方法創建的<select>的末尾添加<option>

現在我有

f.collection_select(:category_id , @categories, :id, :name, {:prompt => 'Please select a category'})

產生

<select id="product_category_id" name="product[category_id]">
  <option value="">Please select a category</option>
  <option value="7">category one</option>
  <option value="8">category 2</option>
</select>

我想要的是什么

<select id="product_category_id" name="product[category_id]">
  <option value="">Please select a category</option>
  <option value="7">category one</option>
  <option value="8">category 2</option>
  <option value="new">..or create a new one</option>
</select>

這是可能的還是我應該循環遍歷集合並手動生成選項?

您可能應該使用select

像這樣:

f.select(:category_id, @categories.collect {|p| [ p.name, p.id ] } + [ [ 'Or create a new one', 'new' ] ], {:include_blank => 'Please select a category'})

祝好運!

同意簡短回答否和長期回答“狡猾”,但這就是我剛才所做的事情,我認為這比這兩種解決方案中的任何一種都簡單並為我工作:

將下一行包含在erb標記內,即<%=%>

f.collection_select :advertisement_group_id, AdvertisementGroup.find(:all, :order => "name DESC") << AdvertisementGroup.new(:name => "New Group"), :id, :name, :include_blank => true  

只需使用.new創建一個新對象,並傳入您想要顯示的任何文本:include_blank => true

我無法發表評論,否則我會將其添加到上面的答案中。

要獲得選項 - >值“新”,“或創建一個新的”而不是

f.select(:category_id, @categories.collect {|p| [ p.name, p.id ] } + ['Or create a new one','new'], {:include_blank => 'Please select a category'})

f.select(:category_id, @categories.collect {|p| [ p.name, p.id ] } + [['Or create a new one','new']], {:include_blank => 'Please select a category'})

注意選項周圍的額外[]。 這使得數組作為選項,值對工作

簡答:不。

答案很長:當然可以,但你必須狡猾。

  • 像這樣創建一個類:

     class New_option_placeholder def id "new" end def name "...or create a new one" end end 
  • 不要傳遞@categories ,而是傳遞@categories+New_option_placeholder.new

如果(正如評論所示)你正在尋找一些可能require "ostruct" ,然后傳遞@categories + [OpenStruct.new(:id => 'new',:name => '...or create a new one')]基本上完成相同的這個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM