如何将"has_many"关联和字段从一个集合移动到另一个集合?



我对RoR很陌生。抱歉,如果我用错了术语或者答案很明显。

最初我有一个用户模型如下,

class User
  include Mongoid::Document
  devise :database_authenticatable,
         :registerable,
         :recoverable,
         :rememberable,
         :trackable,
         :validatable,
         :token_authenticatable,
         :omniauthable
  has_many :foos
  field :name, :type => String
  # Some other company fields
  ....
end
class Foo
  include Mongoid::Document
  belongs_to :user
  ...
end

用来表示公司的初始User模型。

然后我决定添加另一个模型,它将具有与初始User模型不同的角色,因此我开始使用多态关联并将必要的字段从User模型移动到Company模型。我还添加了一个Manager模型,它与Company没有直接关系。我基本上使用用户模型设计。

class User
  include Mongoid::Document
  devise :database_authenticatable,
         :registerable,
         :recoverable,
         :rememberable,
         :trackable,
         :validatable,
         :token_authenticatable,
         :omniauthable
  belongs_to :rolable, :polymorphic => true
end
class Company
  include Mongoid::Document
  has_one :user, :as => :rolable
  has_many :foos
  field :name, :type => String
  # Some other company fields
  ....
end
class Manager
  include Mongoid::Document
  has_one :user, :as => rolable
end
class Foo
  include Mongoid::Document
  belongs_to :company
  ...
end

到目前为止,新用户注册似乎一切正常。但是,我必须转换旧的数据库。让我困惑的是我之前的has_many关联。我已经实现了迁移(使用此gem, https://github.com/adacosta/mongoid_rails_migrations),将字段从User模型移动到Company模型,但是我仍然不知道如何处理关联。

如果您不需要将信息从旧数据库传输到新数据库,则不需要运行迁移。

MongoDB可以在文档上有一些无用的键,没有问题。您可能遇到的唯一问题是在数据库中保存额外的八位字节。

相关内容

最新更新