在rails group_label_method中获取人/定义的名称

时间:2015-09-27 18:06:52

标签: ruby-on-rails simple-form

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

ActiveRecord::Schema.define(version: 20150927111830) do

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.string   "fullname"
    t.string   "avatar_file_name"
    t.string   "avatar_content_type"
    t.integer  "avatar_file_size"
    t.datetime "avatar_updated_at"
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string   "provider"
    t.string   "uid"
    t.string   "image"
  end

  add_index "users", ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end

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

1 个答案:

答案 0 :(得分:0)

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

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