问题
In order to remain DRY, I have a class ModelBase that includes Mongoid document as follows:
class ModelBase
include Mongoid::Document
alias_attribute :guid, :id
def as_json(options = {})
azove_hash = options.merge(:methods => :guid)
super azove_hash
end
end
then all my models inherit from ModelBase and they seem to be working fine. However, there is one model where I use CarrierWave. when it inherits from ModelBase, the call to mount_uploader fails. And when I include the model inside with no subclassing it works fine. Isn't it possible to use carrierwave in a class that inherits from another class?
Here is the version of the class that is failing. would appreciate any suggestion/idea
require 'carrierwave/orm/mongoid'
class SomeOtherModel < ModelBase
field :abstract
validates :abstract, :presence => true
field :category
validates :category, :presence => true, :inclusion => {:in => %w{audio graphics text video}}
field :content_uri
validates :content_uri, :presence => true
has_and_belongs_to_many :topics
has_and_belongs_to_many :events
has_and_belongs_to_many :authors, :class_name => "User"
mount_uploader :content, ContentUploader
attr_accessible :abstract, :category, :content, :content_uri, :authors, :topics, :events
end
回答1:
I think you're making things too complicated. I see no need to inherit from modelbase with a mongoid document. Mongoid itself doesn't use inheritance, and simply includes modules as needed.
So if you have a set of fields re-used, such as contact information, just do something like:
class Customer
include Mongoid::Document
include DataModules::ContactDocument
mounts_uploader :logo, LogoUploader
end
class User
inclue Mongoid::Document
include DataModules::ContactDocument
end
Then include the code that you want to reuse in /lib/data_modules/contact_document.rb
module DataModules::ContactDocument
def self.included(receiver)
receiver.class_eval do
field :email, :type=>String
...
validates_existence_of :email
end
end
end
来源:https://stackoverflow.com/questions/6214384/mongoid-and-carrierwave