validation for hash column in rails
i am having a Users table (id,name,...) and a user_details table(id,user_id,additional_details,designation)
where this additional_details is a hash with (:em开发者_如何学Cpid,:prjt)
I am trying to add validations for the additional_details[:empid] and designation column. How to do that ??
With a custom validation in user details: eg if we want to check that empid is not blank:
#in UserDetail
validate :additional_details_is_valid
def additional_details_is_valid
if !self.additional_details.is_a?(Hash) || self.additional_details[:empid].blank?
self.errors.add(:additional_details, "Empid is blank")
end
end
Now, we simply need to make the User object check that its associated user_detail object is valid.
#in User
validates_associated :user_detail
Now, if empid is not set the UserDetail object will complain, and this in turn will make the user object complain when you try to save it.
精彩评论