无需验证即更新序列化字段?

时间:2013-08-27 00:10:12

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

class Foo
  store :custom_fields, accessors: [:bar1, :bar2, :bar3]

  validates :bar1, presence: true
  validates :bar3, presence: true
end

foo = Foo.new
foo.bar1 = 'hello'
foo.bar2 = 'hello again'

foo.save(validate: false) # => foo is now saved in the database

foo.update(bar2: 'an update to bar2') # => ERROR! since bar3 fails validation

无论如何都要更新而不进行验证?我找到了update_columns方法,但它似乎不适用于像Active Record Store这样的序列化数据。

另一种方法是每次调用foo.save(validate:false),但我真的想更新我的数据,而不是每次都插入一条新记录。

1 个答案:

答案 0 :(得分:2)

您应该只需更新属性,然后调用save:

foo.bar2 = 'an update to bar2'
foo.save(validate: false)