改变从一个关联到许多人多对多 [英] change association from one to many to many to many

查看:118
本文介绍了改变从一个关联到许多人多对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个型号可以假设

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

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.

推荐答案

多对多意味着你的另外两个,所以你可以只创建这一个,写有关吧,毕竟,你可以删除连接表(模型)垃圾IDS从B点。

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.

A,B都没有好名字;)

A, B are not good names;)

假设有用户和评论,而你决定的意见可以有也很多用户,所以它可以是这样的:

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

这篇关于改变从一个关联到许多人多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆