How to update attributes without validation

I have a model with its checks, and I found out that I cannot update the attribute without checking the object before.

I already tried to add the syntax on => :create at the end of each line of validation, but I got the same results.

My ad model has 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 

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 outputs all validation exceptions for this model to the output file.

Can anyone update an attribute without checking the model?

+79
validation ruby-on-rails
Jun 08 '10 at 15:27
source share
6 answers

USE update_attribute instead of update_attributes

Updates a single attribute and saves the record without going through the normal validation procedure.

 if a.update_attribute('state', a.state) 

Note: - "update_attribute" updates only one attribute at a time from the code specified in the question, I think it will work for you.

+117
Jun 08 '10 at 15:33
source share

You can do something like:

 object.attribute = value object.save(:validate => false) 
+134
Feb 28 2018-12-12T00:
source share

try using

 @record.assign_attributes({ ... }) @record.save(validate: false) 

works for me

+44
Jun 03 '15 at 10:27
source share

Yo can use:

 a.update_column :state, a.state 

Check out: http://apidock.com/rails/ActiveRecord/Persistence/update_column

Updates a single attribute of an object without causing a save.

+17
Sep 25 '13 at 15:52
source share

All validation from the model is skipped when we use validate: false

 user = User.new(....) user.save(validate: false) 
+3
Aug 26 '15 at 1:49 on
source share

Must not be

 validates_length_of :title, :in => 6..255, :on => :create 

why does it only work during creation?

-one
Nov 24 '10 at 11:08
source share



All Articles