【发布时间】:2011-11-27 06:49:05
【问题描述】:
我对 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
这个初始用户模型用来代表一家公司。
然后我决定添加另一个模型,该模型将具有与初始用户模型不同的角色,因此我开始使用多态关联并将必要的字段从用户模型移动到公司模型。我还添加了一个与 Company 没有直接关系的 Manager 模型。我基本上使用用户模型进行设计。
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)将字段从用户模型移动到公司模型,但我还是不知道如何处理关联。
【问题讨论】:
-
我最终编写了一个迁移来将必要的字段移动到新模型中。我仍然想知道是否还有其他可能的解决方案。
标签: ruby-on-rails migration mongoid has-many