Austin York
Austin York

Reputation: 838

Mongoid: How to validate value of specific key on Hash field?

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?

Upvotes: 3

Views: 4044

Answers (2)

tagCincy
tagCincy

Reputation: 1599

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

Upvotes: 7

mu is too short
mu is too short

Reputation: 434665

Are you sure you want details to be a simple Hash? If it has structure then it should probably be an embedded document. Then you would put the validation inside that embedded document.

class Whatever
  include Mongoid::Document
  embeds_one :details
  validates :details, :presence => true
end
class Detail
  include Mongoid::Document
  embedded_in :whatever
  field :fullName
  validates :fullName, :presence => true
end

The embedded document would still be a Hash as far as MongoDB itself is concerned so the index and storage would be the same, the only differences will be that Mongoid will know something about the details internals and there will be the usual _id field inside details.

Upvotes: 6

Related Questions