2013-07-17 31 views
0

这甚至可能吗?更改Mongoid班级名称中产

我有一个名为Magazine的mongoid类,也有一些关联,我想重新命名为Publication。问题是我已经有一群已经制作杂志,问题和文章的用户。

原始Magazine型号:

class Magazine 
    # 1. Include mongoid stuff 
    include Mongoid::Document 
    include Mongoid::Timestamps 
    include Mongoid::Slug 

    # 2. Define fields 
    field :title, type: String 
    field :description, type: String 
    field :live, type: Boolean, default: false 
    field :show_walkthrough, type: Boolean, default: true 

    # 3. Set attributes accesible 
    attr_accessible :title, :description, :live, :show_walkthrough, :cover_image_attributes, :logo_image_attributes 

    # 4. Set slug 
    slug :title 

    # 5. Set associations 
    belongs_to :user 
    has_many :issues, dependent: :delete, autosave: true 
    has_one :foreword, :as => :articleable, :class_name => 'Article', dependent: :delete, autosave: true 
    embeds_one :cover_image, :as => :imageable, :class_name => 'Image', cascade_callbacks: true, autobuild: true 
    embeds_one :logo_image, :as => :imageable, :class_name => 'Image', cascade_callbacks: true, autobuild: true 

    # 6. Accepting nested attributes 
    accepts_nested_attributes_for :cover_image, :allow_destroy => true 
    accepts_nested_attributes_for :logo_image, :allow_destroy => true 

    # 7. Set validations 
    validates_presence_of :title, :description, :cover_image, :logo_image 
end 

我知道我可以在类的名称更改为Publication,然后在MongoDB的做db.magazines.renameCollection("publications"),但协会不跟随。

有什么建议吗?

+0

这真的不可能吗?正如我所看到的,我基本上只需要更改关系名称以及集合名称。但我不知道该怎么做。 –

回答

0

我看起来像您的问题和前言模型中的关联字段可能指的是杂志。所以如果你很高兴能改变这个类和底层集合的名字,那么重命名这些关联字段是你的主要问题。你可能有这样的事情:

class Issue 
    belongs_to :magazine 
end 

你可以重新定义该协会为belongs_to :publication。假设您很高兴在您的代码中修复所有对Issue#magazine的引用,那么您的剩余问题是您的issues集合将充满具有magazine_id字段而非publication_field的文档。您有两个选项来修复数据库映射。

第一个选项是重命名数据库中的字段。见mongoDB : renaming column name in collection

第二个选项是使得它通过覆盖“的外键”名称映射到旧的数据库字段来声明关联:

belongs_to :publication, foreign_key: :magazine_id 

你将不得不重复此为前言模型和任何其他参考Magazine

+0

谢谢澄清。如果我做了选项1,重命名集合中的列名,那么所有的publication_id都消失了。这不好。如果我使用选项2(我认为应该是:belongs_to:publication,foreign_key :: magazine_id),那么我会保留该ID,但该关联仍然不起作用。我在这里做错了什么? –

+0

你说得对 - 我把belongs_to弄错了,我会更新它。至于选项1,当您将'magazine_id'重命名为'publication_id'时,它应该保留这些值。你可以在mongo shell中检查吗?如果这样做并且该协会被重新命名为“发布”,那么它应该起作用。 – Steve

+0

将magazine_id重命名为publication_id时,它会保留magazine_id,但关系不再起作用。关系破裂。这是为什么? –

0

只是为了多态性和类继承。

Mongoid通过将类名称存储为文档属性来处理继承和多态关联。

在类本身,这被存储为"_type"属性

对于多态关联像belongs_to :polymorphic_class mongoid添加属性"polymorphic_class_type",使得类可以解决(使用Rails' .constantize)浏览时多态关联。因此,如果您决定更改类名称,并且您有继承或多态关联,那么您还必须重写所有这些属性!