字符串到序列化数组?

时间:2011-01-17 08:47:38

标签: ruby-on-rails arrays string activerecord model

我确信这是微不足道的,但过去几个小时我一直在敲桌子。我正在尝试将字符串(即“key1,key2 :)转换为数组(即[”key1“,”key2“]),然后将其存储在数据库中。我在我的模型中使用了before_validation回调函数似乎没有被解雇。

我的模型看起来像这样:

class Product < ActiveRecord::Base
  serialize :keywords, Array
  attr_accessible :keywords

  before_validation :update_keywords

  def update_keywords
    self.update_attributes(:keywords, self.keywords.split(',').collect(&:strip)
  end
end

我收到了SerializationTypeMismatch错误。显然,update_keywords方法没有运行或没有正确返回更新的属性。

有什么想法吗?

修改
我正在使用Rails 3.0.3,如果这有任何区别。

编辑#2
只是想跟进并说我发现删除序列化列类型声明并确保它默认为空数组(即[])而不是nil清除了许多问题。

为了像我这样的人开始使用Rails的旅程,我应该注意,这很可能是创建序列化属性的最佳方式。我只是移植了一个利用旧数据库的项目。

2 个答案:

答案 0 :(得分:6)

更改update_keywords的实施,如下所示:

def update_keywords
  if keywords_changed? and keywords.is_a?(String)
    self.keywords = keywords.split(',').collect(&:strip) 
  end
end

update_attributes更新数据库属性而不是对象属性。为了给对象属性赋值 使用赋值运算符。

product.name = "Camping Gear"
product.keywords = "camping, sports"

product.save
#  ---- 
#  - "update_attributes" updates the table
#  - "save" persists current state of the object(with `keywords` set to string.)
#  - "save" fails as `keywords` is not an array
#  ---

在解决方案中,changed?检查确保仅在关键字值更改时才运行数组转换代码。

答案 1 :(得分:0)

试试这个

def update_keywords
  self.keywords = self.keywords.split(",").map(&:strip) if self.keywords.is_a?(String)
end
相关问题