简体   繁体   English

ActiveSupport ::关注和扩展mongoid模型

[英]ActiveSupport::Concern and extending mongoid model

I am using mongoid with rails 3 and have come lately to a very tough problem and I need an advice. 我正在使用mongoid和rails 3,并且最近遇到了一个非常棘手的问题,我需要一个建议。

I am working on a CMS and one of the ideas was that CMS would provide some basic models definitions and end user would, if needed, extend basic class with its own definitions and controls and save them in different collections (tables). 我正在研究CMS,其中一个想法是CMS将提供一些基本的模型定义,如果需要,最终用户可以使用自己的定义和控件扩展基本类,并将它们保存在不同的集合(表)中。

class DcPage
  include Mongoid::Document

  field a ....
  belongs_to b ....
  validates a ....
end

class MyPage < DcPage
  field c ....
  validates c ....
end

Up until last version of mongoid this worked (with little hack) and data would be saved to my_pages collection. 直到最后一个版本的mongoid这个工作(很少黑客),数据将保存到my_pages集合。 Because of some problem, mongoid no longer support this behaviour and data always gets saved to dc_pages collection. 由于某些问题,mongoid不再支持此行为,数据始终保存到dc_pages集合。

When explaining my problem, mongoid team suggested that I use ActiveSupport::Concern and provided me with an example. 在解释我的问题时,mongoid团队建议我使用ActiveSupport :: Concern并为我提供了一个示例。 Which works perfectly OK if extended class is defined in same source file. 如果扩展类在同一源文件中定义,那么它的工作正常。 Which btw. 顺便说一句。 never happens in praxis. 从未发生在实践中。

module CommonBehaviour
  extend ActiveSupport::Concern

  included do
    field :subject, type: String, default: ''
    # ...
  end
end

class DcPage
  include Mongoid::Document
  include CommonBehaviour
end

class MyPage
  include Mongoid::Document
  include CommonBehaviour
end

So far I have found out that it works if I require basic source file in my second file. 到目前为止,我发现如果我在第二个文件中需要基本源文件,它可以工作。 Which looks like this: require '/some/path/to/my/gem/app/models/dc_page.rb 看起来像这样:require'/some/path/to/my/gem/app/models/dc_page.rb

Can you can see my pain now. 你现在能看到我的痛苦吗? Basic source file would of course be backed into gem and therefor becomes a moving target. 基本源文件当然会被备份到gem中,因此成为一个移动目标。

Please help me with better solution. 请帮我更好的解决方案。

by TheR 由TheR

The reason this doesn't work is because this is the pattern for single table inheritance. 这不起作用的原因是因为这是单表继承的模式。 You would need to turn off table inheritance in order for this to work. 您需要关闭表继承才能使其正常工作。

However, the suggestion from the mongoid devs is the correct route to go in this case. 但是,在这种情况下,来自mongoid devs的建议是正确的路线。 It looks like you just need to require your module/classes correctly. 看起来你只需要正确地需要你的模块/类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM