0

这甚至可能吗?

我有一个名为 的 mongoid 类Magazine,还有一些关联,我想将其重命名为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然后db.magazines.renameCollection( "publications" )在 mongodb 上执行,但关联并没有遵循。

有什么建议么?

4

2 回答 2

0

我看起来你的问题和前言模型中有关联字段,可能是指杂志。因此,如果您很乐意更改类和基础集合的名称,那么重命名这些关联字段是您的主要问题。你可能有类似的东西:

class Issue
  belongs_to :magazine
end

您可以将此关联重新定义为belongs_to :publication. 假设您很乐意修复Issue#magazine代码中的所有引用,那么您剩下的问题是您的issues集合将充满具有magazine_id字段而不是publication_field. 您有两个选项来修复数据库映射。

第一个选项是重命名数据库中的字段。请参阅mongoDB:重命名集合中的列名

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

belongs_to :publication, foreign_key: :magazine_id

您必须对前言模型和任何其他引用的模型重复此操作Magazine

于 2013-07-18T07:44:59.840 回答
0

只是多态性和类继承的提示。

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

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

对于像belongs_to :polymorphic_classmongoid 这样的多态关联,添加了一个属性,以便在浏览多态关联时"polymorphic_class_type"可以解析该类(使用 Rails' )。.constantize

因此,如果您决定更改类名,并且您有继承或多态关联,那么您还必须重写所有这些属性!

于 2017-03-10T13:38:59.200 回答