字符串数组格式序列

字符串数组格式序列

本文介绍了字符串数组格式序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定,这是微不足道的,但我一直在敲打我的头靠在办公桌的最后几个小时。我想一个字符串(例如转换键1,键2 :)到一个数组(如[键1,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
只是想跟进,并说,我发现,除去序列化列类型声明,并确保它默认为空数组(即[])而不是零清除了许多问题。

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 = self.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 attributeuse 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
#  ---

在该解决方案中,更改?检查确保该数组转换code运行,只有当关键字值的变化。

In the solution, the changed? check makes sure that the array conversion code is run only when the keywords value changes.

这篇关于字符串数组格式序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 07:29