D
D
Denis Savitsky2012-11-19 01:39:56
PostgreSQL
Denis Savitsky, 2012-11-19 01:39:56

What is the best way to store a Hash of the location of objects in a DB?

Can I create a model that will, for example, store the following structure in one field:

{1 => { "x" => 100, "y" => 200}, 2 => { "x" => 420, "y" => 300 }}

I would like this entity to also be able to find these objects, like has_many.
I have not yet seen such solutions - there is not enough experience.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Michael, 2012-11-27
@mshakhan

Didn't quite understand the question. If you just store a hash in the field, that is, serialize:

class User < ActiveRecord::Base
  serialize :preferences
end

user = User.create(:preferences => { "background" => "black", "display" => large })
User.find(user.id).preferences # => { "background" => "black", "display" => large }

M
mercurial, 2012-12-15
@mercurial

To store such models, it is better to use NoSQL solutions such as MongoDB or CoachDB , if used correctly - Redis is also a good option.
In the case of PostgreSQL , you can also use the relatively new hstore feature .
First, you will need to translate the migrations method to sql, since hstore is a specific format column.
You can do this in the config file of application.rbyour application:

config.active_record.schema_format = :sql

Then add activerecord-postgres-hstore gem to Gemfileyour application and generate hstore:setup:
$ rails g hstore:setup

This migration will enable the extension hstorefor your database.
And voila! hstorenow you can use in generating migrations of your tables:
$ rails g migration add_properties_to_table properties:hstore

Besides the fact that type columns hstorework the same way as serializable strings, they can be used in a select (select) and even made indexable for faster searches. Please refer to the documentation (links above) for more details.

O
Otkrick, 2012-11-23
@Otkrick

dht doesn't work?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question