在 rails group_label_method 中获取 human/defined 个名字

Get human/defined name in rails group_label_method

我在 Rails 中有一个 grouped_select 使用 2 个模型。模型本身的名称为 Foo::Bar 和 Foo::Baz。如何让 optgroup 标签成为 Bar 和 Baz 而不是 Foo::Bar 和 Foo::Baz?

 <%= f.input :global_superzone,  collection: [Foo::Bar, Foo::Baz], as: :grouped_select,
 group_method: :all, group_label_method: :model_name,
 label_method: :name, value_method: :to_global_id , :include_blank => false %>

这是我需要更改的 group_label_method: :model_name,但如果我在其中放置任何其他内容,它会引发错误,例如:model_name.human。我也尝试向模型添加一个方法,但也失败了。

一种方法是创建一个模块:

module HumanName
  extend ActiveSupport::Concern

  class_methods do
    def human_name
      model_name.human
    end
  end
end

并将其包含到我们感兴趣的每个模型中:

class Foo::Bar
  include HumanName
end

# etc.

最后更新 group_label_method 选项:

group_label_method: :human_name