【问题标题】:Validation for Translation class I18n::Backend::ActiveRecord::Translation Rails翻译类 I18n::Backend::ActiveRecord::Translation Rails 的验证
【发布时间】:2014-07-23 13:39:27
【问题描述】:

我使用 gem i18n-active_record 翻译我网站中的数据并将翻译保存在数据库中。我已授予管理员编辑翻译的权限。一切正常。

但是这个更新数据的错误部分是管理员可以在没有任何数据(值)的情况下更新翻译,这可能会破坏应用程序,所以我希望把 此类的验证。

如果我这样使用

class Translation < ActiveRecord::Base
  validates :value, :presence => { :message => "Please enter your value" }
end

它不工作。

即使我尝试过使用回调和作用域,它们似乎都不起作用。

任何解决方案或参考请完成它。

【问题讨论】:

    标签: validation activerecord ruby-on-rails-4


    【解决方案1】:

    您是否尝试过将此约束直接放在“值”表字段中?

    这就是它在这里的表现:

    >> class Translation < ActiveRecord::Base
    >>   validates :value, :presence => { :message => "Please enter your value" }
    >>   end
    => {:presence=>{:message=>"Please enter your value"}}
    >> Translation.new.tap { |t| p t.valid?; p t.errors }
    false
    #<ActiveModel::Errors:0x007fce0f11aa78 @base=#<Translation id: nil, value: nil>, @messages={:value=>["can't be blank", "Please enter your value", "Please enter your value"]}>
    => #<Translation id: nil, value: nil>
    >> Translation.new(value: "").tap { |t| p t.valid?; p t.errors }
    false
    #<ActiveModel::Errors:0x007fce0f0f3798 @base=#<Translation id: nil, value: "">, @messages={:value=>["can't be blank", "Please enter your value", "Please enter your value"]}>
    => #<Translation id: nil, value: "">
    >> Translation.new(value: "something").tap { |t| p t.valid?; p t.errors }
    true
    #<ActiveModel::Errors:0x007fce0f0cb540 @base=#<Translation id: nil, value: "something">, @messages={}>
    => #<Translation id: nil, value: "something">
    

    【讨论】:

    • 嗨弗兰克,不,它正在工作。我也尝试过,但没有运气。如果该类是从 activemodel 继承的,则答案可以正常工作,这是另一种情况。如果我们使用 gem "i18n-active_record",翻译类继承自 I18n::Backend::ActiveRecord::Translation。我已经在控制台中尝试过与您的代码类似的尝试,我得到了这样的输出 Translation.new(value: "").tap { |t| p t. 有效吗? p t.errors } 真
    • 查看完整的错误报告 Translation.new.tap { |t| p t. 有效吗? p t.errors } true <:backend::activerecord::translation id: nil value:> Translation.new(value: "").tap { |t| p t. 有效吗? p t.errors } true <:backend::activerecord::translation id: nil created_at: updated_at:>, @messages={}> Translation.new(value: "something").tap { | t| p t. 有效吗? p t.errors } true <:backend::activerecord::translation id: nil value:><:backend::activerecord::translation id: nil>
    • FWIW,I18n::Backend::ActiveRecord::Translation inherits from ActiveModel through ActiveRecord::Base。你能粘贴I18n::Backend::ActiveRecord::Translation.ancestors的结果吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 2011-10-11
    • 1970-01-01
    相关资源
    最近更新 更多