【问题标题】:Localisation of attributes in Rails virtual modelsRails 虚拟模型中的属性本地化
【发布时间】:2013-09-19 04:52:33
【问题描述】:

我在 Rails 3 中创建了一个虚拟(非持久)模型(见下文)

我现在需要对模型应用翻译,但标准翻译位置似乎不起作用。例如

en:
  activerecord:
    attributes:
      media_upload:
        title: "My Title"

我知道我可以使用可选的字符串参数将其直接应用于标签,例如。 f.label :title, t('activerecord.attributes.media_upload') 但这不适用于验证产生的错误消息。同样,我可以按照Localise nested virtual attribute in Rails 中的建议为标签助手的翻译文件添加一个键,但这也无法用于验证。

helpers:
  label:
    media_upload:
      title: "My Title"

除了重新定义所有相关的验证消息之外,还有其他方法可以在非持久模型中进行属性本地化吗??

示例模型如下所示,

class MediaUpload
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :media_file, :title

  validates_presence_of :media_file
  validates_presence_of :title

  def initialize(attributes = {})
    unless attributes.nil?
      attributes.each do |name, value|
        send("#{name}=", value)
      end
    end
  end

  def persisted?
    false
  end
end

【问题讨论】:

  • 您必须在 activerecord.errors.models.admin.attributes.name.blank activerecord.errors.models.admin.blank activerecord.errors.models.user.attributes 中使用 activemodel 代替 activerecord .name.blank activerecord.errors.models.user.blank activerecord.errors.messages.blank errors.attributes.name.blank errors.messages.blank 例如 activemodel: attributes: user: login: "Login" email: "Email" first_name:“名字”错误:模型:用户:属性:登录:is_invalid:“^不正确的登录”
  • 这个问题你解决了吗?

标签: ruby-on-rails ruby-on-rails-3 localization rails-i18n


【解决方案1】:

你需要这样写:

en:
  activemodel:
    attributes:
      media_upload:
        title: "My Title"

不是activerecord 替换为activemodel

【讨论】:

    【解决方案2】:

    您似乎正在使用 simple_form gem 来生成表单。

    所以跟随i18n chapter from github 你的国际化文件应该是这样的

    en:
      simple_form:
        labels:
          media_upload:
            media_file: My File
            title: My Title
    

    如果您使用的是 Rails 4,那么有一种更简单的方法可以创建 ActiveModel Form Objects。你可以像这样include ActiveModel::Model

    class MediaUpload
      include ActiveModel::Model
    
      attr_accessor :media_file, :title
    
      validates_presence_of :media_file
      validates_presence_of :title
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-11
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多