Search code examples
ruby-on-railsactiverecordhashstrong-parameters

Save a hash to a parameter?


I would like to save the params from the form submitted into a hash called: hash_options which corresponds to a field in my table.

  1. How do I store the hash of: hash_options as the value for: hash_fields ?
    • hash_fields is a text field and I am trying to store hash_options in this row as a plain hash.

def person_params
  hash_options = {age: params['person']['age'], location: params['person']['location'], gender: params['person']['gender']}
  params.require(:person).permit(:first_name, :last_name, :owner, hash_fields: [hash_options])
end

Side question: How does the model access and store the params?


Solution

  • In order to be able to save the hash as is to the database you have a couple of options:

    1. If you are using MongoDB(mongoid) you can just define it as a hash type field in your model with:

      field options_hash, type: Hash

    2. You can use postgresql HStore to save schemaless data into that column which enables you to save the hash into the column and work with it as a Hash.

    As for the params part there is no need to include it in the permit call, you can just do:

    model = Model.new(person_params) do |m|
      m.options_hash = hash_options
    end
    
    model.save