Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在选项上使用辅助对象进行选择_Ruby On Rails_Ruby On Rails 5 - Fatal编程技术网

Ruby on rails 在选项上使用辅助对象进行选择

Ruby on rails 在选项上使用辅助对象进行选择,ruby-on-rails,ruby-on-rails-5,Ruby On Rails,Ruby On Rails 5,我有一个选择,一年中的所有月份都是数字1、2、3…12,还有一个将月份的数字转换为名称的方法。例:1->1月,2->2月 我想在select上使用它,显示月份的名称而不是数字 我的问题是,如何生成一个select,并将此方法传递给下面的选项 提前感谢您可以使用成对数组获得单独的文本和值: options_for_select([["January", 1], ["February", 2]]) # => <option value="1">January</option&

我有一个选择,一年中的所有月份都是数字1、2、3…12,还有一个将月份的数字转换为名称的方法。例:1->1月,2->2月

我想在select上使用它,显示月份的名称而不是数字

我的问题是,如何生成一个select,并将此方法传递给下面的选项


提前感谢

您可以使用成对数组获得单独的文本和值:

options_for_select([["January", 1], ["February", 2]])
# => <option value="1">January</option>
# => <option value="2">February</option>
.zip将两个数组合并成对。drop1是必需的,因为month_names数组中的第一个元素为nil,没有month 0

<div class="ls-custom-select">
  <%=
    form.select(
        :month,
        options_for_select(
          (1..12).to_a.zip(I18n.t("date.month_names").drop(1),
          @current_month # selected
        )
        {},
        { class: "ls-select" }
    )
  %>
</div>

您不需要编写方法来获取月份名称。使用I18n.tdate.month_名称[编号]。或者,如果本地化不重要,请使用Date::MONTHNAMES[number]。

您不需要编写获取月份名称的方法。使用I18n.tdate.month\u names[number]。最大值很好!你的解决方案解决了我的疑问:。我只是稍微改变了一下,以便更合身。再次感谢!这里是:还有一个问题,如果我删除第一个元素nil,会有问题吗?
(1..12).to_a.zip(I18n.t("date.month_names").drop(1))
# => [[1, "January"], [2, "February"], [3, "March"], [4, "April"], [5, "May"], [6, "June"], [7, "July"], [8, "August"], [9, "September"], [10, "October"], [11, "November"], [12, "December"]]
<div class="ls-custom-select">
  <%=
    form.select(
        :month,
        options_for_select(
          (1..12).to_a.zip(I18n.t("date.month_names").drop(1),
          @current_month # selected
        )
        {},
        { class: "ls-select" }
    )
  %>
</div>