【问题标题】:rails form select helper not respecting "selected"rails form select helper不尊重“选择”
【发布时间】:2015-12-07 12:46:06
【问题描述】:

我正在尝试使用 rails 表单 select 助手来设置选定的选项。选择正确呈现表单,但 selected 属性未得到尊重。这是我尝试过的:

  <%= form.select :time_of_day, options_for_select({
    "AM" => "1",
    "PM" => "2"}), "2" %>

这不起作用。我试过了:

  <%= form.select :time_of_day, options_for_select({
    "AM" => "1",
    "PM" => "2"}), {selected: "2"} %>

这也不起作用。我虽然可能会感到困惑,所以我也尝试了:

  <%= form.select :time_of_day, options_for_select({
    "AM" => "1",
    "PM" => "2"}), {selected:  "PM"} %>

但这也不起作用。我一定在更根本的层面上做错了什么。如何使选定的状态起作用?

【问题讨论】:

    标签: ruby-on-rails forms drop-down-menu helper helpers


    【解决方案1】:

    您可以使用以下表格:

    <%= form.select "time_of_day", [['AM',1], ['PM', 2]], { selected: 2 }  %>
    # or
    <%= form.select "time_of_day", {'AM' => 1, 'PM' => 2}, { selected: 2 }  %>
    

    但我会简单地推荐:

    <%= form.select "time_of_day", ['AM','PM'], { selected: 'AM' }  %>
    

    您可以从这里找到有关select helper 的更多信息:

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

    【讨论】:

      【解决方案2】:

      options_for_select 一起使用时,语法会略有变化。以下应该可以工作。

      <%= form.select :time_of_day, options_for_select( {"AM" => "1", "PM" => "2"}, "2") %>
      

      生成的HTML选项会是这样的

      <option value="1">AM</option>
      <option value="2" selected="selected">PM</option>
      

      欲了解更多信息,请参阅options_for_select

      【讨论】:

        【解决方案3】:

        让我们声明一个变量:

        time_day = {
            "AM" => "1",
            "PM" => "2"}
        

        现在在表格中,

        <%= form.select :time_of_day, options_for_select(time_day.each_pair{|key,val| [key, val]}, :selected => "PM")  %>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-05
          • 2019-10-28
          • 1970-01-01
          相关资源
          最近更新 更多