【问题标题】:Convert rails select_date to int将 rails select_date 转换为 int
【发布时间】:2015-04-19 23:25:33
【问题描述】:

我有两个date_selects 需要以整数形式提交。我的印象是我的解决方案过于复杂。

问题:

<%= f.date_select :month_num, :discard_year => 'true', :discard_day => 'true', :use_month_numbers => 'true', :prompt => {:month => "Select month"} %>

<%= f.date_select :year_num, :order => [:year], :start_year => Time.now.year, :end_year => Time.now.year + 5, :prompt => {:year => "Select year"} %>

以上这些方法都不作为整数提交。

要解决这个问题,我可以简单地执行以下操作:

<%= f.select :month_num, options_for_select([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]]) %>

<%= f.select :year_num, options_for_select([[Time.now.year], [Time.now.year + 1], [Time.now.year + 2], [Time.now.year + 3], [Time.now.year + 4], [Time.now.year + 5]]) %>

但这很丑陋,必须有一种更清洁的方法。

我可以使用我原来的方法将这些作为整数提交吗?

【问题讨论】:

    标签: ruby-on-rails date select


    【解决方案1】:

    据我了解,date_select 将始终将值作为日期提供。如果您想简化补救措施的语法,您可以使用视图助手来生成选项值,例如,

    <%= f.select :month_num, options_for_select(get_month_ints) %>
    

    在 app/helpers/my_view_helper.rb 中

    module MyViewHelper
      def get_month_ints
        [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]]
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-18
      • 2011-04-20
      • 1970-01-01
      • 2020-07-03
      • 2012-01-07
      • 1970-01-01
      • 2018-04-28
      • 2011-05-13
      相关资源
      最近更新 更多