Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

like image 626
Damjan Rems Avatar asked Nov 12 '22 06:11

Damjan Rems


1 Answers

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.

like image 53
cpuguy83 Avatar answered Nov 27 '22 08:11

cpuguy83