5

I am using mongoid with rails 3 and have come lately to a very tough problem and I need an advice.

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).

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. Because of some problem, mongoid no longer support this behaviour and data always gets saved to dc_pages collection.

When explaining my problem, mongoid team suggested that I use ActiveSupport::Concern and provided me with an example. 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

Can you can see my pain now. Basic source file would of course be backed into gem and therefor becomes a moving target.

Please help me with better solution.

by TheR

Damjan Rems
  • 101
  • 1
  • 3
  • 1
    Are you adding the common functionality directly to the gem source? Which class are you trying to alter? – Chris Apr 28 '13 at 18:22
  • I assume that CommonBehaviour modul and DcPage class are in the same source file ../app/models/dc_page.rb which is contained inside gem file. MyPage class is defined inside current application as ../app/models/my_page.rb and it would extend DcPage class. In this scenario it includes CommonBehaviur module which is included in both classes. – Damjan Rems Apr 29 '13 at 05:36
  • Did you ever find a better solution to this? I am having the same issue. – Adam Albrecht May 23 '13 at 16:13

1 Answers1

1

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. It looks like you just need to require your module/classes correctly.

cpuguy83
  • 5,794
  • 4
  • 18
  • 24