Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何在一列发生更改时保存和更新另一列_Sql_Ruby On Rails_Ruby - Fatal编程技术网

Sql 如何在一列发生更改时保存和更新另一列

Sql 如何在一列发生更改时保存和更新另一列,sql,ruby-on-rails,ruby,Sql,Ruby On Rails,Ruby,我有一个text类型的数据库列,它在我的数据库中存储一个散列 column_a = {sample_list: [{email: test@gmail.com},{email: test2@gmail.com}]} 我想在数据库中生成另一列,其中包含电子邮件地址字符串,例如: column_B = "test@gmail.com,test2@gmail.com" 我知道如何从散列中获取并生成字符串,我的问题是我必须进行哪些模型更改,以便每当填充column_A时,column_B都应该更新

我有一个text类型的数据库列,它在我的数据库中存储一个散列

column_a = {sample_list: [{email: test@gmail.com},{email: test2@gmail.com}]}
我想在数据库中生成另一列,其中包含电子邮件地址字符串,例如:

column_B = "test@gmail.com,test2@gmail.com"
我知道如何从散列中获取并生成字符串,我的问题是我必须进行哪些模型更改,以便每当填充
column_A
时,
column_B
都应该更新


在这种情况下,我如何处理历史数据的迁移?

我会选择这个选项,但是Steven应该使用类似于:
self.comlumn\u b=…
,以便同一个数据库提交保存两列。这就是为什么我在调用save之前使用
。我不知道他用什么代码来更新
列b
,但我假设它会执行
self.column\u b=
而不是直接的数据库调用。保存前在
调用中所做的任何更改都会保留在保存中。是的,你说得对。我刚才提到这一点是为了让他知道;-)。
class ClassName < ApplicationRecord
  before_save :maybe_update_column_b

  def maybe_update_column_b
    update_column_b if column_a_changed?
  end

  def update_column_b
    #your code to update column b
  end
end
ClassName.find_each  do |cn| 
  cn.update_column_b
  cn.save
end