Lei Wang
Lei Wang

Reputation: 562

rails how to get hash in database

there is a column "config" in table "mytable", when I get data it show like that:

a = Mytable.last
a.config
=> '{\"states\"=>[\"us\", \"uk\"], \"sexes\"=>[\"1\", \"0\"], \"grades\"=>[\"2012\", \"2013\", \"2014\", \"2015\"]}'
a.config["grades"]
=> error

how I get the data unless using eval.

Upvotes: 0

Views: 938

Answers (2)

max
max

Reputation: 102026

You can use serialize like in the accepted answer to to store the hash as a string in the database. However a huge con is that the serialized data cannot be queried. You have to pull the data out of the database to be able to use it in any meaningful way.

If you are using a Postgres or a newer version of MySQL you can declare your database column as a JSON type column. Postgres also has a hstore type which is stored as key/value. All of these allow you to query and index the data stored in the column.

create_table :monsters do |t|
  t.json 'characteristics'
end

# lets find the cookie monster
Monster.where("characteristics->>'addiction' = ?", "cookies")

Upvotes: 1

wang
wang

Reputation: 26

you should serialize your column in your model:

serialize :config, JSON

then you can use like your example.

Upvotes: 1

Related Questions