Rails 3 NoMethodError(未定义的方法`unserialized_value' for" --- [] \ n":String):

时间:2014-07-15 13:21:39

标签: ruby ruby-on-rails-3 postgresql serialization yaml

我正在使用Rails 3.2.13和postgress。 我仅在production server

中收到错误
NoMethodError (undefined method `unserialized_value' for "--- []\n":String):
  app/controllers/blogs_controller.rb:159:in `content_generators'

我正在序列化Array以将其存储在db中。下面是代码。

控制器

class BlogsController < ApplicationController
  def content_generators
    @blog = Blog.find(params[:id])
    @users = @blog.content_generators.map do |id|
      User.find(id)
    end
  end
end

模型

class Blog < ActiveRecord::Base
  serialize :post_access, Array
  serialize :content_generators, Array
  attr_accessible :post_access, :content_generators
end

移植

class AddContentgeneratorsToBlog < ActiveRecord::Migration
  def change
    add_column :blogs, :content_generators, :string, :default => [].to_yaml
  end
end

我已经使用了序列化。您可以看到post_access已序列化。这很完美。 但现在当我添加另一列content_generators时,它开始破坏。 感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

由于您使用的是postgresql,我强烈建议您使用内置数组功能:

# Gemfile
gem 'postgres_ext'

class MyMigration
  def change
    add_column :my_table, :that_array_column, :text, array: true, default: []
  end
end

然后移除模型中的serialize次来电。 PG序列化数组的行为与模型上的YAML序列化数组完全相同,除了db支持它们的一些查询方法。