【问题标题】:Change Rail Model attribute's label更改 Rail Model 属性的标签
【发布时间】:2016-09-01 09:29:46
【问题描述】:

这是我的模型:

class Post
  include Mongoid::Document
  include Mongoid::Timestamps

  belongs_to :user, optional: true
  has_many :comments

  field :title, type: String
  field :body, type: String

  validates :title, presence: true
  validates :body, presence: true

end

当我在正文字段上收到验证错误时,我得到“正文不能为空白”,我想在模型中将其更改为“内容不能为空白”。如何更改字段标签?

【问题讨论】:

    标签: ruby-on-rails mongoid


    【解决方案1】:

    您可以在config/locales/en.yml 中通过覆盖模型的属性标签来做到这一点:

    en:
    ...
      activerecord:
        attributes:
          post:
            body: 'Content'
    

    对于Mongoid,将上面的activerecord 替换为mongoid。如果这不起作用,请尝试:

    en:
      mongoid:
        attributes:
          body: 'Content'
    

    这被称为 I18n 的翻译过程。有了这个,您基本上可以覆盖任何模型的命名等(例如,用户 --> 客户)、属性、错误消息等。除此之外,您还可以拥有其他文件,如 es-CO.yml,以将翻译目标定位到其他开箱即用的语言。

    您可以阅读有关translation here 的更多信息。

    【讨论】:

    • 将上面的activerecord 替换为mongoid
    • @kiddorails 不应该在attributesbody 之间存在一个级别post,就像在活动记录的第一个示例中一样?或者这会改变所有模型中的所有身体属性吗?
    【解决方案2】:

    将此添加到config/locales/en.yml

    en:
      activerecord:
        attributes:
          post:
            body: "Content"
    

    这会在给出错误时更改属性名称

    【讨论】:

    • body 必须是“内容”而不是“帖子”。
    猜你喜欢
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 2020-05-16
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多