将关联从一个更改为多个到多个到多个

时间:2014-08-25 18:45:33

标签: mysql ruby-on-rails postgresql activerecord many-to-many

我假设有两个模型

class A < ActiveRecord::Base
  has_many :bs
end
class B < ActiveRecord::Base
  belogns_to :a
end

现在因为一些系统更改我需要将这种关联转换为很多很多东西,比如这个

class A < ActiveRecord::Base
  has_and_belongs_to_many :bs
end
class B < ActiveRecord::Base
  has_and_belongs_to_many :as
end

OR

class A < ActiveRecord::Base
  has_many :cs
  has_many :bs, through: :cs
end
class B < ActiveRecord::Base
  has_many :cs
  has_many :as, through: :cs
end
class C < ActiveRecord::Base
  belongs_to :a
  belongs_to :b
end

最好的方法是什么,最重要的是我不想丢失我现有的数据。现有记录应自动采用这些更改。提前谢谢。

1 个答案:

答案 0 :(得分:0)

很多对很多意味着你在另外两个之间连接了表(模型),所以你可以创建这个并写入它的关系,然后就可以从B中删除垃圾ID。

A,B不是好名字;)

假设您有用户和评论,并且您认为评论也可以包含许多用户,因此它看起来像:

class User
  has_many :comments # will be changed

  has_many :user_comments
end

class UserComments
  belong_to :user
  belong_to :comment
end

class Comment
  belong_to :user # id will be removed from table and relation will be changed

  has_many :user_comments
end

# as direction for import could be something like:

User.all.each do |user|
  user.comments.each do |comment|
    UserComments.create user: user, comment: comment
  end
end
相关问题