how to build a select tag from a range in rails

后端 未结 4 2411
太阳男子
太阳男子 2021-02-20 02:37

I want to have a drop down that consists of values 10% 20% 30% so on till 100.

In ruby It can be done by

(10..100).step(10) { |i| p i }
相关标签:
4条回答
  • 2021-02-20 03:17
    <%= select("sale", "discount", (10..100).step(10).collect {|p| [ "#{p}%", p ] }, { :include_blank => true }) %>
    
    0 讨论(0)
  • 2021-02-20 03:24

    Without Providing a Formatted Value.

    If you landed here, like me, without the need to use step() or to provide a formatted value (e.g. "20%"), this is a nice and succinct method:

    <%= f.select :year, (2011..Date.today.year).to_a %>
    
    <select id="report_year" name="report[year]">
      <option value="2011">2011</option>
      <option value="2012">2012</option>
      <option value="2013">2013</option>
      <option value="2014">2014</option>
      <option value="2015">2015</option>
    </select>
    

    With a Default

    <%= f.select :year, options_for_select( (2011..Date.today.year).to_a, Date.today.year ) %>
    
    <select id="report_year" name="report[year]">
      <option value="2011">2011</option>
      <option value="2012">2012</option>
      <option value="2013">2013</option>
      <option value="2014">2014</option>
      <option value="2015" selected="selected">2015</option>
    </select>
    
    0 讨论(0)
  • 2021-02-20 03:40

    #step returns an enumerator (or yields, as you've shown). It looks like what you want is to call #collect on this enumerator.

    <%=p.select :thc, options_for_select((10..100).step(10).collect {|s| ["#{s}%", s]})%>

    0 讨论(0)
  • 2021-02-20 03:44

    You almost had it:

    <%=p.select :thc, options_for_select((10..100).step(10).to_a.map{|s| ["#{s}%", s]})%>
    
    0 讨论(0)
提交回复
热议问题