Search code examples
ruby-on-railspostgresqljsonb

How to fix keys in a jsonb field


I have a table with one jsonb field. I want that field to have onlye three keys, say the table schema is

name: string dob: date personal_data: jsonb

i want personal_data to have only three keys personal_data: { mothers_name: '', father_name: '', random_key: ''

}

if i try to save some other key, it should show an error. I am using rails, any way to achieve this


Solution

  • this will handle two specific keys and any random 3rd key. If you want 3 specific keys only add the third key to the array and (self....).count == 3 instead of 2

    On yourmodel.rb

    before_save :check_personal_data

    keys_to_always_match = [ :mothers_name, :father_name ]
    
    def check_personal_data
      (self.personal_data.keys & keys_to_always_match).count == 2 && self.personal_data.count == 3 
    end
    

    You'll probably also want to add a default value to the migration:

    t.jsonb :personal_data, default: { mothers_name: '', father_name: '', random_key: '' }
    

    The elegant solution for the key matching comes from:

    Testing if a hash has any of a number of keys