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

…衆ロ難τιáo~ 提交于 2019-12-13 01:25:53

问题


I want my ActiveRecord class User to contain options (a bunch of string key-values), so I wrote:

rails generate migration 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?


回答1:


To have ruby object as an attribute of the ActiveRecord model you should use serialize method inside your class for that attribute link




回答2:


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


来源:https://stackoverflow.com/questions/6594409/how-to-add-a-hash-object-to-an-activerecord-class-tried-but-migration-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!