2011-11-27 88 views
2

我是RoR的新手。对不起,如果我使用错误的术语或答案是显而易见的。如何将“has_many”关联和字段从一个集合移动到另一个集合?

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

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 

用于表示公司此初始用户模型。

然后我决定添加另一个模型,它与初始用户模型有不同的作用,所以我开始使用多态关联并将必要的字段从用户移动到公司模型。我还添加了一个与公司无直接关系的经理模型。我基本上使用用户模型的设计。

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协会。我已经实现了迁移(使用此创业板,https://github.com/adacosta/mongoid_rails_migrations)将字段从用户模型移动到公司模型,但我再也找不到如何处理这些关联。

+0

我最终编写了一个迁移程序,将必要的字段移到新模型中。我仍然想知道是否有其他可能的解决方案。 – ertan

回答

1

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

MongoDB在文档上可以有一些无用的键,没有问题。唯一的问题是可以在数据库中保存多余的八位字节。

相关问题