In Mongoid, I can set an index on the attribute of a field whose type is Hash as follows:
index({ "details.fullName" => 1 }, { name: "full_name_index" })
What I'd like to do is create validations for such entities using something like the following:
validates "details.fullName", presence: true
Unfortunately, this produces the following error:
NoMethodError: undefined method `details.fullName' for Thing
Did I make a syntax mistake, or is this feature simply not supported in Mongoid 3?
Since Hash data type is unstructured hash value (i.e. it doesn't have any reference to the keys inside the hash, you can literally stick any hash string in there), you will have to write a custom validation method:
validate :details_has_full_name
def details_has_full_name
errors.add(:details, "Some Error Message") if details["fullName"].nil?
end