Reputation: 1955
I'm trying to call validation on an ActiveRecord after a certain method in another Ruby file is called. Is there some way I can tie this into ActiveRecord's validation scheme, i.e.:
validate :cars_have_wheels?, on: after_cache_reset
Note: cars_have_wheels?
is a method located in the ActiveRecord object, after_cache_reset
is the method in the other file.
Thank you!
Upvotes: 1
Views: 3061
Reputation: 8131
Check out this link (Ruby on Rails guides):
5 Conditional Validation Sometimes it will make sense to validate an object only when a given predicate is satisfied. You can do that by using the :if and :unless options, which can take a symbol, a string, a Proc or an Array. You may use the :if option when you want to specify when the validation should happen. If you want to specify when the validation should not happen, then you may use the :unless option.
5.1 Using a Symbol with :if and :unless You can associate the :if and :unless options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option.
class Order < ActiveRecord::Base
validates :card_number, presence: true, if: :paid_with_card?
def paid_with_card?
payment_type == "card"
end
end
Upvotes: 4