Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

html - Rails' collection_select helper method and the "Create item" option at the end

Is it possible to add an <option> at the end of a <select> created with the collection_select helper method?

Right now I have

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

which generates

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

and what I would like is

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

Is this possible or should I just loop through the collection and generate the options manually?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should probably use select instead.

Like so:

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

Good luck!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...