如何在没有验证的情况下更新属性 [英] How to update attributes without validation
问题描述
我有一个带有验证的模型,但我发现如果不验证对象就无法更新属性.
I've got a model with its validations, and I found out that I can't update an attribute without validating the object before.
我已经尝试在 => 上添加 :create
语法在每个验证行的末尾,但我得到了相同的结果.
I already tried to add on => :create
syntax at the end of each validation line, but I got the same results.
我的公告模型有以下验证:
My announcement model have the following validations:
validates_presence_of :title
validates_presence_of :description
validates_presence_of :announcement_type_id
validate :validates_publication_date
validate :validates_start_date
validate :validates_start_end_dates
validate :validates_category
validate :validates_province
validates_length_of :title, :in => 6..255, :on => :save
validates_length_of :subtitle, :in => 0..255, :on => :save
validates_length_of :subtitle, :in => 0..255, :on => :save
validates_length_of :place, :in => 0..50, :on => :save
validates_numericality_of :vacants, :greater_than_or_equal_to => 0, :only_integer => true
validates_numericality_of :price, :greater_than_or_equal_to => 0, :only_integer => true
我的 rake 任务执行以下操作:
My rake task does the following:
task :announcements_expiration => :environment do
announcements = Announcement.expired
announcements.each do |a|
#Gets the user that owns the announcement
user = User.find(a.user_id)
puts a.title + '...'
a.state = 'deactivated'
if a.update_attributes(:state => a.state)
puts 'state changed to deactivated'
else
a.errors.each do |e|
puts e
end
end
end
这会在输出中抛出该模型的所有验证异常.
This throws all the validation exceptions for that model, in the output.
有没有人如何在不验证模型的情况下更新属性?
Does anybody how to update an attribute without validating the model?
推荐答案
USE update_attribute 而不是 update_attributes
更新单个属性并保存记录,无需通过正常的验证程序.
Updates a single attribute and saves the record without going through the normal validation procedure.
if a.update_attribute('state', a.state)
注意:- 'update_attribute' 一次只更新一个属性,我认为它对你有用.
Note:- 'update_attribute' update only one attribute at a time from the code given in question i think it will work for you.
这篇关于如何在没有验证的情况下更新属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!