How to write database specific custom validator in Rails 3.0?
I need to write a custom validator to check if a record exists in the database or not. Sort of like the opposite of validate uniqueness, however I couldn't find something that could achieve what I wanted in the built in validators.
What I'm attempting to do is check if the referrer exists or not in the User开发者_高级运维s table. If the referrer's username is "testuser", I want to check in the Users table whether "testuser" actually exists.
I have created a custom validator:
class ReferrerExistsValidator < ActiveModel::EachValidator
However I'm unsure how to proceed to fetch details from there database, any pointers?
Write the following validation class
class ReferrerExistsValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless User.find_by_username(value)
object.errors[attribute] << (options[:message] || "referrer does not exist")
end
end
end
Add the following to the relevant model
validates :referrer_exists => true
I'm new to rails/coding, and I may misunderstand you, but couldnt you just do something like:
@user.each do |user|
unless @user.username == current_user.referral_name
:alert "no user found"
else whatever
end
end
EDIT: that wouldn't work at all - ignore that, let me think about it for a sec ;)
精彩评论