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

前端 未结 4 1132
死守一世寂寞
死守一世寂寞 2020-12-31 09:34

Is it possible to add an at the end of a

提交评论

  • 2020-12-31 09:51

    Agreed on the short answer No and long answer " Be Crafty ", but here's what I just did which I think is simpler than either of these two solutions and worked for me:

    Wrap the next line inside erb tags i.e. <%= and %>:

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

    Just create a new object with .new and pass in whatever text you want displayed along with :include_blank => true.

    0 讨论(0)
  • 2020-12-31 10:00

    I can't comment otherwise I'd add this to the answer above.

    To get the option->value "new","or create a new one".. instead of

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

    do

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

    note the extra [] around the options. This makes the array work as an option,value pair

    0 讨论(0)
  • 2020-12-31 10:01

    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!

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