【问题标题】:Multiple select with custom data使用自定义数据进行多选
【发布时间】:2021-01-29 14:13:15
【问题描述】:

我有一个这样的多选表单:

.form-row__select
        = f.collection_check_boxes(:game_ids, @games, :id, :name)

@games 集合之所以有效,是因为数据是以这种方式返回的:

=> #<Game:0x00007fa12c3a9560
 id: 5,
 name: :example,
 active: true,
 ...

但现在我需要将自定义数据添加到我的集合中,但我无法使多选工作:

game = Game.enabled.includes(:category)
    @games = game.map do |s|
       [[s.category.name, I18n.t(s.type_code, scope: 'enum.type.name')].join(' - '), s.id]
    end
@games.sort!

上述方法的结果是这样的数组数组:

[["Example one - Category X", 5],
["Example four - Category Y", 1]]
...

如何使用上面的数组进行多项选择并显示其字符串以便可以选择它们? 非常感谢您的帮助!

【问题讨论】:

    标签: arrays ruby-on-rails checkbox


    【解决方案1】:
    class Game < ApplicationRecord
      # ...
      def my_fancy_pants_name
        [s.category.name, I18n.t(s.type_code, scope: 'enum.type.name')].join(' - ')
      end
    end
    
    .form-row__select
       = f.collection_check_boxes(:game_ids, @games, :id, :my_fancy_pants_name, multiple: true)
    

    如果您对将这个逻辑放入模型感到困扰,您可以使用装饰器。您还可以传递一个块以进一步自定义输入和标签,详细信息in the docs

    【讨论】:

    • 感谢您的帮助,非常感谢。我能够按照您的建议将该方法添加到模型中并且它有效。但是,我现在遇到了另一个问题:我似乎无法对返回的字符串进行排序。我需要将它们按字母顺序排列。以前我能够做到这一点,因为我曾经映射所有这些并在方法的末尾放置一个“排序”,如您在上面的示例中所见。请您对我如何将它们整理好有什么建议吗?非常感谢。
    • @games.sort(&:my_fancy_pants_name)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    相关资源
    最近更新 更多