Answer the question
In order to leave comments, you need to log in
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 }}
Answer the question
In order to leave comments, you need to log in
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 }
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.rb
your application:
config.active_record.schema_format = :sql
Gemfile
your application and generate hstore:setup
:$ rails g hstore:setup
hstore
for your database. hstore
now you can use in generating migrations of your tables:$ rails g migration add_properties_to_table properties:hstore
hstore
work 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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question