【问题标题】:Rails' select tag helper not selecting existing valueRails 的选择标签助手不选择现有值
【发布时间】:2013-07-26 10:14:00
【问题描述】:

我在 Rails 3.2.14 中为表单使用选择助手标签:

<%= f.label :male, 'Gender' %>
<%= f.select :male, [['Girl', 0], ['Boy', 1]]  %>

GirlBoy 菜单项显示在下拉列表中,但即使数据库中的 male 设置为 1,也永远不会选择 Boymale 实际上是schema.rb 中的boolean 值。

如果maletrue,我如何让f.select 标签自动选择Boy

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2


    【解决方案1】:

    其实你需要调用options_for_select,在这里你可以定义选择哪个选项。示例:

    options = options_for_select [['Girl', 0], ['Boy', 1]], 1
    f.select :male, options
    

    会输出select标签,它的选项,Boy会被选中。

    --

    您也可以查看options_from_collection_for_select,最初设计用于记录集合,例如:

    options_from_collection_for_select @users, :id, :name
    

    id 作为值和name 作为文本生成选项。 options_from_collection_for_select 基本上可以在任何地方使用

    coll = %w[cheese garlic]
    options_from_collection_for_select coll, :to_s, :humanize
    

    也可以

    【讨论】:

    • 我确实需要options_for_select,我玩过,但问题是我需要使用resource.male ? 1 : 0 作为options_for_select 的第二个参数。我不知道我可以使用resource.attribute(使用设计)。
    【解决方案2】:

    试试这个,

    f.object.male %>

    从此stackoverflow question获得更多选择

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多