skip certain validation method in Model - ruby-on-rails

I am using Rails v2.3
If I have a model:
class car < ActiveRecord::Base
validate :method_1, :method_2, :method_3
...
# custom validation methods
def method_1
...
end
def method_2
...
end
def method_3
...
end
end
As you see above, I have 3 custom validation methods, and I use them for model validation.
If I have another method in this model class which save an new instance of the model like following:
# "flag" here is NOT a DB based attribute
def save_special_car flag
new_car=Car.new(...)
new_car.save #how to skip validation method_2 if flag==true
end
I would like to skip the validation of method_2 in this particular method for saving new car, how to skip the certain validation method?

Update your model to this
class Car < ActiveRecord::Base
# depending on how you deal with mass-assignment
# protection in newer Rails versions,
# you might want to uncomment this line
#
# attr_accessible :skip_method_2
attr_accessor :skip_method_2
validate :method_1, :method_3
validate :method_2, unless: :skip_method_2
private # encapsulation is cool, so we are cool
# custom validation methods
def method_1
# ...
end
def method_2
# ...
end
def method_3
# ...
end
end
Then in your controller put:
def save_special_car
new_car=Car.new(skip_method_2: true)
new_car.save
end
If you're getting :flag via params variable in your controller, you can use
def save_special_car
new_car=Car.new(skip_method_2: params[:flag].present?)
new_car.save
end

The basic usage of conditional validation is:
class Car < ActiveRecord::Base
validate :method_1
validate :method_2, :if => :perform_validation?
validate :method_3, :unless => :skip_validation?
def perform_validation?
# check some condition
end
def skip_validation?
# check some condition
end
# ... actual validation methods omitted
end
Check out the docs for more details.
Adjusting it to your screnario:
class Car < ActiveRecord::Base
validate :method_1, :method_3
validate :method_2, :unless => :flag?
attr_accessor :flag
def flag?
#flag
end
# ... actual validation methods omitted
end
car = Car.new(...)
car.flag = true
car.save

Another technique, which applies more to a migration script than application code, is to redefine the validation method to not do anything:
def save_special_car
new_car=Car.new
new_car.define_singleton_method(:method_2) {}
new_car.save
end
#method_2 is now redefined to do nothing on the instance new_car.

Use block in your validation something like :
validates_presence_of :your_field, :if => lambda{|e| e.your_flag ...your condition}

Depending on weather flag is true of false, use the method save(false) to skip validation.

Related

Run block defined on class within instance's scope

I would like to create something similar to ActiveRecord validation: before_validate do ... end. I am not sure how could I reference attributes of class instance from the block given. Any idea?
class Something
attr_accessor :x
def self.before_validate(&block)
#before_validate_block = block
end
before_validate do
self.x.downcase
end
def validate!
# how should this method look like?
# I would like that block would be able to access instance attributes
end
end
#3limin4t0r's answer covers mimicing the behavior in plain ruby very well. But if your are working in Rails you don't need to reinvent the wheel just because you're not using ActiveRecord.
You can use ActiveModel::Callbacks to define callbacks in any plain old ruby object:
class Something
extend ActiveModel::Callbacks
define_model_callbacks :validate, scope: :name
before_validate do
self.x.downcase
end
def validate!
run_callbacks :validate do
# do validations here
end
end
end
Featurewise it blows the socks off any of the answers you'll get here. It lets define callbacks before, after and around the event and handles multiple callbacks per event.
If validations are what you really are after though you can just include ActiveModel::Validations which gives you all the validations except of course validates_uniqueness_of which is defined by ActiveRecord.
ActiveModel::Model includes all the modules that make up the rails models API and is a good choice if your are declaring a virtual model.
This can be achieved by using instance_eval or instance_exec.
class Something
attr_accessor :x
# You need a way to retrieve the block when working with the
# instance of the class. So I've changed the method so it
# returns the +#before_validate_block+ when no block is given.
# You could also add a new method to do this.
def self.before_validate(&block)
if block
#before_validate_block = block
else
#before_validate_block
end
end
before_validate do
self.x.downcase
end
def validate!
block = self.class.before_validate # retrieve the block
instance_eval(&block) # execute it in instance context
end
end
How about this?
class Something
attr_accessor :x
class << self
attr_reader :before_validate_blocks
def before_validate(&block)
#before_validate_blocks ||= []
#before_validate_blocks << block
end
end
def validate!
blocks = self.class.before_validate_blocks
blocks.each {|b| instance_eval(&b)}
end
end
Something.before_validate do
puts x.downcase
end
Something.before_validate do
puts x.size
end
something = Something.new
something.x = 'FOO'
something.validate! # => "foo\n3\n"
This version allows us to define multiple validations.

Inline `after_commit` Callbacks in Rails

I've got a sidekiq job that needs to be run after the commit, but only in some situations and not all, in order to avoid a common race condition.
For example, the below after_commit will always fire but the code inside will only execute if the flag is true (previously set in the verify method).
class User < ActiveRecord::Base
...
after_commit do |user|
if #enqueue_some_job
SomeJob.new(user).enqueue
#enqueue_some_job = nil
end
end
def verify
#enqueue_some_job = ...
...
save!
end
end
The code is a bit ugly. I'd much rather be able to somehow wrap the callback inline like this:
class User < ActiveRecord::Base
def verify
if ...
run_after_commit do |user|
SomeJob.new(user).enqueue
end
end
...
save!
end
end
Does anything built into Rails exist to support a syntax like this (that doesn't rely on setting a temporary instance variable)? Or do any libraries exist that extend Rails to add a syntax like this?
Found a solution using a via a concern. The snippet gets reused enough that it is probably a better option to abstract the instance variable and form a reusable pattern. It doesn't handle returns (not sure which are supported via after_commit since no transaction is present to roll back.
app/models/concerns/callbackable.rb
module Callbackable
extend ActiveSupport::Concern
included do
after_commit do |resource|
if #_execute_after_commit
#_execute_after_commit.each do |callback|
callback.call(resource)
end
#_execute_after_commit = nil
end
end
end
def execute_after_commit(&callback)
if callback
#_execute_after_commit ||= []
#_execute_after_commit << callback
end
end
end
app/models/user.rb
class User < ActiveRecord::Base
include Callbackable
def verify
if ...
execute_after_commit do |user|
SomeJob.new(user).enqueue
end
end
...
save!
end
end
You can use a method name instead of a block when declaring callbacks:
class User < ActiveRecord::Base
after_commit :do_something!
def do_something!
end
end
To set a condition on the callback you can use the if and unless options. Note that these are just hash options - not keywords.
You can use a method name or a lambda:
class User < ActiveRecord::Base
after_commit :do_something!, if: -> { self.some_value > 2 }
after_commit :do_something!, unless: :something?
def do_something!
end
def something?
true || false
end
end
Assuming that you need to verify a user after create.
after_commit :run_sidekiq_job, on: :create
after_commit :run_sidekiq_job, on: [:create, :update] // if you want on update as well.
This will ensure that your job will run only after a commit to db.
Then define your job that has to be performed.
def run_sidekiq_job
---------------
---------------
end
Hope it helps you :)

How to detect if a paperclip attachment was changed in after_save callback?

It looks like Paperclip doesn't honor the ActiveRecord dirty model. How do I detect the change in after_save callback.
class User
has_attachment :avatar
after_save :do_something
def do_something
if name_changed?
#
end
# How to determine avatar was changed?
#if avatar_changed?
# #
#end
end
end
Note
I know I can detect the change in before_save callback using avatar.dirty? call, but the dirty flag is set to false after save.
I can add a processor, but I need to perform my actions after the model data is saved.
You could try accessing the _changed? method for one of the attributes:
if avatar_updated_at_changed?
# do something
end
When I need access to this data after save, I typically take this approach:
class Foo
has_attachment :avatar
before_save :check_for_avatar_changes
after_save :do_something
def do_something
if #avatar_has_changes
#
end
end
def check_for_avatar_changes
#avatar_has_changes = self.avatar.dirty?
end
end

Use super with before_validation

I have this code in my every model.
Class people
def before_validation
#attributes.each do |key,value|
self[key] = nil if value.blank?
end
end
end
Now i want to put my loop in separate module. Like
Module test
def before_validation
#attributes.each do |key,value|
self[key] = nil if value.blank?
end
end
end
And i want to call this before_validation this way
Class people
include test
def before_validation
super
.....Here is my other logic part.....
end
end
Are there any way to do it like that in rails??
You can setup multiple methods to be called by the before_validation callback. So instead of straight up defining the before_validation, you can pass the methods you want to get called before validation.
module Test
def some_test_before_validaiton_method
# do something
end
end
class People < ActiveRecord::Base
include Test
def people_before_validation_foo
#do something else
end
before_validation :some_test_before_validation_method
before_validation :people_before_validaiton_foo
end
You can read more about callbacks here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

Ruby on Rails ActiveRecord Validation

I would like to validate attributes in a function like this
class User < ActiveRecord::Base
validate :check_name( :name )
def check_name( name )
... if name is invalid ...
self.errors.add( :name, 'Name is invalid')
end
end
Can you please write the right code?
Please explain the functionality why...
THX!
class User < ActiveRecord::Base
validate :check_name
def check_name
if name # is invalid ...
self.errors.add(:name, 'Name is invalid')
end
end
end
You can use the validate macro but the method can't accept parameters.
You need to fetch the attribute value from inside the method, then validate it.
Replace
if name # is invalid ...
with your own validation logic.

Resources