Alex Cortes
Alex Cortes

Reputation: 61

save hash in database in ruby on rails

I'm trying to save a hash in my database but this does not work

this is my table in my database

create_table "categories", force: :cascade do |t|
    t.string  "name",      limit: 255
    t.integer "client_id", limit: 4
    t.integer "event_id",  limit: 4
    t.text    "color",     limit: 65535
  end

in my model try with serialize

class Category < ActiveRecord::Base
  serialize :color, Hash
end

in my controller:

def category_params
      params.require(:category).permit(:name, :color, :event_id)
end

when I try to save it I get this in my console:

 Parameters: {"category"=>{"event_id"=>"2", "name"=>"dwdqwd", "color"=>{"color"=>"#ad1d1d", "opacity"=>1}}}

Unpermitted parameter: color

SQL (0.4ms)  INSERT INTO `categories` (`name`, `event_id`) VALUES ('dwdqwd', 2)

How can I save the hash in my database?

Upvotes: 0

Views: 1033

Answers (1)

max
max

Reputation: 102045

.permit(:color) does not work since a hash is not considered a permitted scalar type.

The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile.

You can whitelist a hash of nested parameters by passing an array of permitted keys:

params.require(:category)
      .permit(:name, :event_id, color: [:color, :opacity])

To allow any keys use an empty hash:

params.require(:category)
      .permit(:name, :event_id, color: {})

See:

Upvotes: 2

Related Questions