Monday, February 15, 2010

Avoid validations on create or update in rails

There might be several situations where we might have to avoid the default validations defined in the model when we update or create a record.
a.)One solution to avoid validation is by doing something like this
@something = Something.find(params[:id])
@something.column_save = 'your data'

respond_to do |format|
if @something.save(false) #save without validation
b.)Another solution is to write a separate method to validate in the model
please see the example below
validate :validates_uniqueness_of_name

def validates_uniqueness_of_name
return if deleted == true
num_duplicates = self.class.count(:conditions => ["name = ? AND deleted = ?",self.name, false])
if num_duplicates > 0
errors.add(:name, :taken)
end
end

No comments:

Post a Comment