【问题标题】:ActiveRecord::RecordInvalid: Validation failed: Key can't be blankActiveRecord::RecordInvalid:验证失败:密钥不能为空
【发布时间】:2019-04-15 15:05:27
【问题描述】:

更新到 Rails 4.0 后,我收到此错误。

ActiveRecord::RecordInvalid (Validation failed: Key can't be blank):
  app/models/users_setting.rb:25:in `update_value'
  app/controllers/management_reports/employee_onboarding_controller.rb:35:in `update_filter_values'
  app/controllers/management_reports/employee_onboarding_controller.rb:57:in `prepare_to_read_data'
  app/controllers/management_reports/employee_onboarding_controller.rb:11:in `index'

这是方法:

def update_value options={}
  binding.pry
    self.update_attributes!({:value => options.inspect})
  end

pry 告诉我这个:

[5] pry(#<UsersSetting>)> self.update_attributes!({:value => options.inspect})
   (5.0ms)  BEGIN
   (5.0ms)  BEGIN
   (4.8ms)  ROLLBACK
   (4.8ms)  ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Key can't be blank
from /Users/justinhung/.rvm/gems/ruby-2.1.10/gems/activerecord-4.0.0/lib/active_record/validations.rb:57:in `save!'
[6] pry(#<UsersSetting>)> options
=> {:status=>"-1", :client_id=>"-100"}
[7] pry(#<UsersSetting>)> :value
=> :value
[8] pry(#<UsersSetting>)> value
=> "{:status=>\"-1\", :client_id=>\"-100\"}"
[9] pry(#<UsersSetting>)> :value => options.inspect
SyntaxError: unexpected =>, expecting end-of-input
:value => options.inspect
         ^
[9] pry(#<UsersSetting>)> options.inspect
=> "{:status=>\"-1\", :client_id=>\"-100\"}"
[10] pry(#<UsersSetting>)> options
=> {:status=>"-1", :client_id=>"-100"}

不知道如何继续,任何帮助将不胜感激。

【问题讨论】:

  • 你期望这是做什么的? self.update_attributes!({:value =&gt; options.inspect})
  • 能否请您发布表的架构
  • 您从哪个版本升级 Rails 应用程序?您是只更新了 Rails 版本还是也更改了任何代码?该模型有哪些验证?
  • 验证UserSetting 必须有key。我们的options 不包含key 的值? key 是否已设置在 UserSetting 上?
  • 这可能是因为从 RoR 4 开始,belongs_to 关系已成为强制性。您是否忘记设置相关记录?

标签: ruby-on-rails ruby activerecord


【解决方案1】:

看到options本身就是一个hash所以你只需要传递options试试,

self.update_attributes!(options)

其中 statusclient_id 是模型属性。

Key can't blank and value can't blank 是 Rails 验证错误消息,因为您可能为这两个字段设置了存在 true。

如果您想跳过验证,您可以执行以下操作,以便在更新 rails 时不要大声要求键和值的存在。

def update_value options={}
  self.status = options[:status]
  self.client_id = options[:client_id]
  self.save(validate: false)
end

【讨论】:

  • 不幸的是,这不起作用,我收到错误:Validation failed: Key can't be blank, Value can't be blank
猜你喜欢
  • 1970-01-01
  • 2017-12-02
  • 1970-01-01
  • 2016-08-16
  • 1970-01-01
  • 2016-07-30
  • 1970-01-01
  • 2020-07-11
  • 1970-01-01
相关资源
最近更新 更多