Ruby on Rails: How to limit the key for Hash Fields in Mongoid?

Viewed 59

For example, I want to allow key home_page only for field url

class Person
  include Mongoid::Document
  field :first_name
  field :url, type: Hash
end

I want this work

def set_vals
  self.first_name = 'Daniel'
  self.url = {'home_page' => 'http://www.homepage.com'}
  save
end

and this fail

def set_vals
  self.first_name = 'Daniel'
  self.url = {'unknown' => 'http://www.homepage.com'}
  save
end
1 Answers

Add a model validation, inspect the keys and add errors to the model if undesired keys are present.

Related