字符串到序列化数组? [英] String to Serialized Array?
问题描述
我确定这很简单,但在过去的几个小时里,我的头一直撞在桌子上.我正在尝试将字符串(即key1,key2:)"转换为数组(即 [key1",key2"]),然后再将其存储到数据库中.我在我的模型中使用了 before_validation 回调,它似乎没有开火.
I'm sure this is trivial, but I've been banging my head against the desk for the last few hours. I'm trying to convert a string (i.e. "key1,key2:) to an array (i.e. ["key1","key2"]) before storing it in the database. I'm using a before_validation callback in my model and it doesn't seem to be firing.
我的模型如下所示:
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 方法没有运行,要么没有正确返回更新的属性.
I'm getting a SerializationTypeMismatch error. Obviously, either the update_keywords method isn't being run or isn't properly returning the updated attributes.
有什么想法吗?
编辑
我正在使用 Rails 3.0.3,如果这有什么不同的话.
EDIT
I'm using Rails 3.0.3, if that makes any difference.
编辑 #2
只是想跟进并说我发现删除序列化列类型声明并确保它默认为空数组(即 [])而不是 nil 可以解决许多问题.
EDIT #2
Just wanted to follow up and say that I've found that removing the serialized columns type declaration and ensuring that it defaults to an empty array (i.e. []) rather than nil clears up many issues.
为了像我这样刚开始使用 Rails 的人,我应该注意这很可能不是创建序列化属性的最佳方式.我只是移植了一个使用旧数据库的项目.
For the sake of anyone like myself just beginning their journey with Rails, I should note that this most likely not the best way to go about creating serialized attributes. I'm just porting over a project that utilizes an old database.
推荐答案
更改 update_keywords
的实现如下:
def update_keywords
if keywords_changed? and keywords.is_a?(String)
self.keywords = keywords.split(',').collect(&:strip)
end
end
update_attributes
更新数据库属性而不是对象属性.为了给对象属性赋值使用赋值运算符.
The update_attributes
updates the DB attribute NOT the object attribute. In order to assign a value to an object attribute
use the assignment operator.
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?
检查确保仅当关键字值更改时才运行数组转换代码.
In the solution, the changed?
check makes sure that the array conversion code is run only when the keywords value changes.
这篇关于字符串到序列化数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!