开发者

validation for hash column in rails

开发者 https://www.devze.com 2023-02-01 23:33 出处:网络
i am having a Users table (id,name,...) and a user_details table(id,user_id,additional_details,designation)

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消