Rails - 创建时清空序列化字段

时间:2014-05-20 19:49:57

标签: ruby-on-rails serialization

如何创建带有序列化数组字段的记录到字符串。

喜欢这个吗?

ExerciseStudent.create(exercise_id: e.id, student_id: self.id, load: "[]", repetition: "[]")

或者像这样简单?

ExerciseStudent.create(exercise_id: e.id, student_id: self.id, load: "", repetition: "")

稍后填写数据时我想看起来像这样:

exercise.load == "[15, 20, 30]"

我的模特:

class ExerciseStudent < ActiveRecord::Base
  serialize :load, Array
  serialize :repetition, Array
  belongs_to :exercise
  belongs_to :student
end

1 个答案:

答案 0 :(得分:1)

不要试图将值表示为String实例,而是全部进入并使用Arrays。由于您已经告诉Rails序列化该属性,因此它会在保存时将其从数组转换为YAML,反之亦然(#34;加载&#34;如同从数据库到对象)在记忆中。)

exercise.load = [15, 20, 30]

ExerciseStudent.create(exercise_id: e.id, student_id: self.id, load: [], repetition: [])