【问题标题】:Mongoid and carrierwaveMongoid和载波
【发布时间】:2011-09-07 01:09:26
【问题描述】:

为了保持 DRY,我有一个 ModelBase 类,其中包含 Mongoid 文档,如下所示:

class ModelBase
  include Mongoid::Document

  alias_attribute :guid, :id

  def as_json(options = {})
    azove_hash = options.merge(:methods => :guid)
    super azove_hash
  end
end

然后我的所有模型都继承自 ModelBase,它们似乎工作正常。但是,有一种型号我使用 CarrierWave。当它从 ModelBase 继承时,对 mount_uploader 的调用失败。当我在没有子类的情况下包含模型时,它工作正常。难道不能在从另一个类继承的类中使用carrierwave吗?

这是失败的类的版本。将不胜感激任何建议/想法

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

【问题讨论】:

    标签: ruby-on-rails mongoid carrierwave


    【解决方案1】:

    我认为你把事情弄得太复杂了。我认为不需要使用 mongoid 文档从模型库继承。 Mongoid 本身不使用继承,只是根据需要包含模块。

    因此,如果您有一组重复使用的字段,例如联系信息,只需执行以下操作:

    class Customer
      include Mongoid::Document
      include DataModules::ContactDocument
      mounts_uploader :logo, LogoUploader
    end
    
    class User
      inclue Mongoid::Document
      include DataModules::ContactDocument
    end
    

    然后在 /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
    

    【讨论】:

    • 杰西,感谢您的回复。实际上,我并没有尝试共享字段。我试图重用我需要的 as_json 方法,因为我在前端使用 Sproutcore,这需要 json 格式进行数据通信。所以,我想在一个类中移动该方法,并在我的所有模型中尽可能多地重用它。但是,当我使用那个特定的类时,它会抛出一个错误:关于 mount_uploader 没有方法错误
    • 将我的方法用于 as_json 方法。不要使用继承
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多