Ruby on Rails: how do I use a default placeholder thing in a select_tag?

后端 未结 3 1468
傲寒
傲寒 2020-12-14 00:18
 <%= select_tag(:services, 
                       options_from_collection_for_select(Service.all, :id, :name))%>

And it displays all the ser

相关标签:
3条回答
  • 2020-12-14 00:40

    Most of the time, you don't want to append anything to the array directly; either of these is a cleaner solution:

    • Use :prompt => "Placeholder" if you want the placeholder to show up only when the attribute is nil at the time the form is rendered. It will be selected by default, but nothing will be saved if user submits. If the attribute is already populated [possibly because a) there's a default value or b) it's an edit form], the placeholder item will be omitted from the list entirely.
    • Use :include_blank => "Placeholder" if you want to include the placeholder in the rendered list at all times.
    0 讨论(0)
  • 2020-12-14 00:49
    <%= select_tag(:services, 
                   Service.all.collect { |c| [c.id, c.name] }.
                   insert(0, "Select a Service"))%>
    

    As answered for the question, this is for Rails 2.3. For Rails 3, see Prathan Thananart's answer.

    0 讨论(0)
  • 2020-12-14 01:02

    The better way to do this would be to use the :prompt parameter. Something like:

    select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {:prompt => 'Select Person'})
    

    http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html

    0 讨论(0)
提交回复
热议问题