2

に依存するアプリケーションを入手しましたCouchbase::Model。すべての厄介なデータベース ハッキングをカプセル化するクラスを作成し、特定の属性を独自の方法で検証する必要があります。そこで、カスタム検証メソッドを作成しました:

class AdServeModel < Couchbase::Model

validate :validate_attributes

[...] (some other stuff happens here)

def validate_attributes
  #First we validate the objects we belong_to
  unless belongsToModels.nil?
    belongsToModels.each do |attribute|
      retrievedClass = attribute.to_s.camelize.constantize.find(
                       send("#{belongsToAttributeName(attrName)}"))
      errors.add(attribute.to_sym, "#{attribute} is invalid") unless !retrievedClass.nil? and retrievedClass.valid?
    end
  end
end

しかし、これを実行しようとすると、次のようになります undefined method 'validate' for AdServeModel(id):Class (NoMethodError)。私はかなり困惑しています。なぜこれが起こるのかについての指針をいただければ幸いです。さらにコードが必要な場合は、コメントでそのように言ってください。

4

1 に答える 1

3

The code looks fine. There are two different methods named validate that I know from Rails, one is for validating records (instance method) and another one (class method) is used for the more general case as it does apply in your scenario.

Adds a validation method or block to the class. This is useful when overriding the validate instance method becomes too unwieldy and you’re looking for more descriptive declaration of your validations.

The documentation shows that you need to include the ActiveModel::Validations module. Yes, Couchbase does include that already in its own ActiveModel module, but only if it is available. My guess is that the problem originates from this line of the Couchbase source code.

return unless defined?(::ActiveModel)

With the :: it accesses the outer module name scope to get the Rails modules. If this module is available, it would continue and include further Rails Active Model modules.

base.class_eval do
  extend ActiveModel::Callbacks
  extend ActiveModel::Naming
  include ActiveModel::Conversion
  include ActiveModel::Validations

Probably, Couchbase it not able to access the Rails module. The best would to check if Couchbase really includes the modules, respectively to get Couchbase find the Rails modules. An alternative/workaround might be to simply include the module yourself.

class AdServeModel < Couchbase::Model
  include ActiveModel::Validations
  # ...
end
于 2013-08-21T21:08:08.113 に答える