【问题标题】:Changing attributes name in en.yml file is not working在 en.yml 文件中更改属性名称不起作用
【发布时间】:2013-01-07 15:48:48
【问题描述】:

我在 ruby​​ on rails 项目中更改了 en.yml 文件中的属性名称。按钮工作正常。但是字段属性没有改变。

这是我的模型,

class Enr::AffordableWarmth < ActiveRecord::Base
  self.table_name = "AffordableWarmth"
  self.primary_key = 'Record_No'

  validates_presence_of :No_Bedrooms, :No_Bedspaces, :Max_Annual_Energy_Cost
  validates :No_Bedrooms, uniqueness: { scope: :No_Bedspaces, 
    message: "already exists!" }
  validates_numericality_of :No_Bedrooms, :No_Bedspaces, :Max_Annual_Energy_Cost
end

zh-CN.yml 文件

en-GB:
  helpers:
    submit:
      enr_rds_dea:
        create: 'Create new user'
        update: 'Update'

      enr_affordable_warmth:
        create: 'Create'
        update: 'Update'

  activerecord:
      models:
        AffordableWarmth:
      attributes:
        AffordableWarmth:
          No_Bedrooms: "Number of Bedrooms"

不过,在 rails 控制台和表单中,它会显示“No Bedrooms could not be blank”。一些代码在活动记录中不起作用。在一些代码工作正常之前。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1


    【解决方案1】:

    查看lib/active_model/errors.rb,我认为键应该是“enr/affordable_warmth”而不是AffordableWarmth,但您可能需要以某种方式指定“Enr”命名空间。

    如果它不起作用,请使用bundle show activemodel 找到已安装的gem 源,然后在lib/active_model/errors.rb 中进行一些调试以找出它所期望的 i18n 密钥。

    更新:

    调试方法如下:

    我搜索 I18n,它进行翻译,所以我找到了方法 generate_message,它生成了整个错误消息,它把翻译后的属性名称作为参数(参见 :attribute 键),这引导我到方法human_attribute_name,我在lib/active_model/translation.rb中找到了。

    我加了一行:

    puts "human_attribute_name(#{attribute.inspect}, #{options.inspect}): defaults: #{defaults.inspect}"

    就在I18n.translate 之前,然后启动我的控制台。

    对于Foo::User 的模型,我得到:

    human_attribute_name("account_type", {}): defaults: [:"activerecord.attributes.foo/user.account_type", :"attributes.account_type", "Account type"]

    所以这应该适合你:

      activerecord:
          attributes:
            "enr/affordable_warmth":
              no_bedrooms: "Number of Bedrooms"
    

    【讨论】:

    • 嗨,谢谢。但是 lib 文件夹内没有 active_model 文件夹。 :(
    • 您是否查看了 activemodel gem 的 lib 文件夹?在我的机器上,它位于这样的目录中:/home/lev/.rvm/gems/ruby-1.9.2-p180@foo/gems/activemodel-3.2.8/lib/active_model/
    • 谢谢。现在,我在 active_model 文件夹中的 error.rb 文件中。但我很困惑,因为它是一个很长的文件。我是 ruby​​ on rails 的新手。我应该在这编辑什么?
    • 在上面的帖子中添加了调试说明
    • 这种模式对我有用。您可以在控制台中尝试I18n.t "activerecord.attributes.enr/affordable_warmth.no_bedrooms",查看翻译文件是否正确加载。尝试在每个级别上缩进 2 个空格,尽管它也适用于我的 4 个空格。
    猜你喜欢
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 2017-08-26
    • 2012-01-18
    • 2018-07-07
    • 2017-04-10
    • 1970-01-01
    相关资源
    最近更新 更多