简体   繁体   English

将关联从一对多改变为多对多

[英]change association from one to many to many to many

I have two models lets suppose 我假设有两个模型

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

now because of some system changes I need to convert this association to many to many some thing like this 现在由于某些系统更改,我需要将此关联转换为多对多的类似

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

what is best way to do this and most importantly I DO NOT WANT TO LOSE MY EXISTING DATA. 最好的方法是什么,最重要的是我不想丢失我的现有数据。 Existing records should automatically adopt these changes. 现有记录应自动采用这些更改。 Thanks in advance. 提前致谢。

many to many means you have connected table(model) between two other, so you could just create this one and write relation to it, after that you could remove garbage ids from B. 多对多表示您已将表(模型)连接在另外两个表之间,因此您可以创建该表并与其建立关系,然后可以从B中删除垃圾ID。

A, B are not good names;) A,B不是好名字;)

imagine you have User and Comments, and you decide that comments can have also many users, so it can look like: 想象您有“用户”和“评论”,并且您决定评论也可以有许多用户,因此它看起来像:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM