【发布时间】:2013-05-04 16:44:40
【问题描述】:
我的模型中有一个多态关联,它在创建时遇到了一个间歇性错误(在生产中)。我修复了它,但现在我需要修复在此错误下创建的条目。
我的模型:
class User < ActiveRecord::Base
belongs_to :userable, :polymorphic => true
attr_protected :userable
end
class UserType1 < ActiveRecord::Base
has_one :user, :as => :userable, :dependent => :destroy
end
class UserType2 < ActiveRecord::Base
has_one :user, :as => :userable, :dependent => :destroy
end
所以,问题是我的用户表上有一些条目与他们的多态表无关。
记录示例(用户表):
id userable_id userable_type
999 null UserType1
并且UserType1没有任何相关的条目。
所以我做了一个查询来检测所有的输入错误:
SELECT users.* from users where COALESCE(userable_id, 0) = 0'
但我不知道如何干净地修复它。
我的想法是创建一个这样的脚本:
User.find_by_sql('SELECT users.* from users where COALESCE(userable_id, 0) = 0').each do |user|
userable = user.userable_type.classify.constantize.new
userable.user = user
userable.save
user.userable = userable
user.save
end
谢谢
【问题讨论】:
-
为什么要构建和保存一个用户?调用 nil 问题的方法?
-
建议标题:“如何编写 rake 任务来操作数据库”
标签: ruby-on-rails activerecord polymorphic-associations