序列化列在Rails中总是作为null保存

时间:2022-06-18 23:27:03

All I am trying to do is save a two-dimensional hash in the column of a database in a Ruby on Rails application. I am only learning the how to use the framework, and this task is causing me a lot of grief. I have done my best to not make any stupid mistakes, though I believe my problem stems from one.

我所要做的就是在Ruby on Rails应用程序的数据库列中保存一个二维散列。我只是在学习如何使用这个框架,这个任务让我很伤心。我已经尽力不犯任何愚蠢的错误,尽管我相信我的问题源于错误。

So what I'm doing is I create the hash in a controller and set it as the value of a field in my object, then call save.

我要做的是在控制器中创建散列并将其设置为对象中字段的值,然后调用save。

Code:

@instance = Model.find(:first, :conditions => "id = 1"}

@instance.hash_field = Hash.new { |h, k| h[k] = Hash.new { |h1, k1| h1[k1] =0 }} 

@instance.other_field = "some string"

@instance.save

other_field will have its new value saved and the value persists on subsequent retrievals from the database. The 'hash_field' will always be reset to nil when I pull the instance out of the database again. This happens despite the fact that the value of '@instance.hash_field' has the correct value in the controller and the view. This allows me to be confident in saying it is an issue with saving the hash to the database.

other_field将保存它的新值,该值将保存到数据库的后续检索中。当我再次从数据库中取出实例时,'hash_field'将始终重置为nil。尽管“@instance”的值是这样的,但还是发生了这种情况。hash_field'在控制器和视图中具有正确的值。这使我确信,将散列保存到数据库是一个问题。

I have the statement

我有声明

:serialize :hash_field

in my model, and its column in the database table is declared to have type 'text.' Any pointers would make me a very happy person.

在我的模型中,它在数据库表中的列被声明为具有type 'text。任何建议都会让我成为一个非常快乐的人。

-Chris

屁股的

2 个解决方案

#1


1  

  1. 'serialize' is a method.
  2. “序列化”是一个方法。
  3. Hash.new { |h, k| h[k] = Hash.new { |h1, k1| h1[k1] =0 }} => {}
  4. 散列。new {|h, k| h[k] = Hash。新{|h1, k1| h1[k1] =0}} => {}
  5. Please provide test data you use for hashes.
  6. 请提供您用于散列的测试数据。

#2


0  

Get rid of the ":" in front of serialize:

去掉“:”前面的序列化:

class Model < ActiveRecord::Base
  serialize :hash_field

end

#1


1  

  1. 'serialize' is a method.
  2. “序列化”是一个方法。
  3. Hash.new { |h, k| h[k] = Hash.new { |h1, k1| h1[k1] =0 }} => {}
  4. 散列。new {|h, k| h[k] = Hash。新{|h1, k1| h1[k1] =0}} => {}
  5. Please provide test data you use for hashes.
  6. 请提供您用于散列的测试数据。

#2


0  

Get rid of the ":" in front of serialize:

去掉“:”前面的序列化:

class Model < ActiveRecord::Base
  serialize :hash_field

end