Rails 3 Validations on Field from Related Model
I have a User class that has a UserProfile class. The email is stored in the User table because they need to login with it, however, from my user_profiles#edit
method, I'd like to be able to update this email address.
How can I place validations on the email field?
My class looks something like this (obviously not right, but you get the idea):
class UserProfile < ActiveRecord::Base
belongs_to :user
validates :first_name, :presence => true
validates :last_name, :presence => true
validates :email, :presence => true, :uniqueness => true, :email_fo开发者_C百科rmat => true
def email=(email)
self.user.email = email
self.user.save
end
end
My form parameters will look something like:
{
"user_profile" => { "first_name" => "John", "email" => "qwerty", ....
}
The EmailValidator is just taken from Railscasts:
class EmailFormatValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
object.errors[attribute] << (options[:message] || "is not formatted properly")
end
end
end
You can put your validation in the user model. When you call save on the user model, then those validations are checked.
And you need to add the following to the association:
belongs_to :user, :validate => true, :autosave => true
And remove the save call from the email= method, because now the user is saved automatically.
精彩评论