【问题标题】:Fix inconsistency with polymorphic association修复与多态关联的不一致
【发布时间】: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


【解决方案1】:
class User
  alias_method :old_userable, :userable

  def userable
    old_userable || Userable.new
  end

end

【讨论】:

    猜你喜欢
    • 2020-06-25
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    相关资源
    最近更新 更多