Eze*_*lin 2 arrays string activerecord model ruby-on-rails
我确信这是微不足道的,但过去几个小时我一直在敲桌子.我正在尝试将字符串(即"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
Run Code Online (Sandbox Code Playgroud)
我收到了SerializationTypeMismatch错误.显然,update_keywords方法没有运行或者没有正确返回更新的属性.
有任何想法吗?
编辑
我正在使用Rails 3.0.3,如果这有任何区别.
编辑#2
只是想跟进并说我发现删除序列化列类型声明并确保它默认为空数组(即[])而不是nil清除了许多问题.
为了像我这样的人开始使用Rails旅行,我应该注意到这很可能不是创建序列化属性的最佳方式.我只是移植了一个利用旧数据库的项目.
更改实现update_keywords
如下:
def update_keywords
if keywords_changed? and keywords.is_a?(String)
self.keywords = keywords.split(',').collect(&:strip)
end
end
Run Code Online (Sandbox Code Playgroud)
在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
# ---
Run Code Online (Sandbox Code Playgroud)
在解决方案中,changed?
检查确保仅在关键字值更改时才运行数组转换代码.