开发者

How to add a Hash object to an ActiveRecord class? Tried but migration fails

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜