Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

ruby - Using Rails serialize to save hash to database

I'm try to save a hash mapping ids to a number of attempts in my rails app. My migration to the database to accommodate this new column:

class AddMultiWrongToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :multi_wrong, :string
  end

  def self.down
    remove_column :users, :multi_wrong
  end
end

In my model I have:

class User < ActiveRecord::Base 
 serialize :multi_wrong, Hash
end

But when I use the rails console to test this by doing:

user = User.create()
user.multi_wrong = {"test"=>"123"}
user.save

The output is false. What's going wrong here?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The column type is wrong. You should use Text instead of String. Therefore, your migration should be:

 def self.up
   add_column :users, :multi_wrong, :text
 end

Then Rails will properly convert it into YAML for you (and perform proper serialization). Strings fields are limited in size and will only hold especially-small values.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...