I want my ActiveRecord class User
to contain options (a bunch of string key-values), so I wrote:
rails generate mi开发者_Python百科gration AddOptionsToUser options:Hash
It generated:
class AddOptionsToUser < ActiveRecord::Migration
def self.up
add_column :users, :options, :Hash
end
def self.down
remove_column :users, :options
end
end
I also added this line to my class User
:
serialize :options, Hash
But the migration fails:
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Hash' at line 1: ALTER TABLE `users` ADD `options` Hash
I am new to Rails, what is the usual way to store a bunch of string key-values in an ActiveRecord class?
Rails serializes things in to a (YAML) string. So in your database, the type should be string (or text).
class AddOptionsToUser < ActiveRecord::Migration
def self.up
add_column :assessments, :options, :string
end
def self.down
remove_column :assessments, :options
end
end
To have ruby object as an attribute of the ActiveRecord model you should use serialize
method inside your class for that attribute link
精彩评论