插件中的验证方法

时间:2011-07-02 13:29:42

标签: ruby-on-rails ruby ruby-on-rails-3 validation plugins

我正在使用Ruby on Rails 3.0.7,我正在尝试为我的应用程序实现一个act_as_article插件。我要做的是为该插件中的“作为文章类”运行验证方法(注意:我的插件需要创建一些数据库表列以便工作 - 其中一个由title属性。)

在我的RoR应用程序中,我有以下代码:

# vendor/plugins/article/lib/acts_as_article.rb
module Article
  extend ActiveSupport::Concern

  included do
    validates :title,  # Validation method
      :presence => true
  end

  module ClassMethods
    def acts_as_article
      send :include, InstanceMethods
    end
  end

  module InstanceMethods
    ...
  end
end

ActiveRecord::Base.send :include, Article


# app/models/review.rb
class Review
  acts_as_article

  ...
end

使用上面的代码插件可以正常工作。但是,如果我在Review类中添加一些记录关联,如下所示:

class Review
  acts_as_article

  has_many :comments # Adding association

  ...
end

并在我的ReviewsController中添加以下内容:

def create
  ...

  @article.comments.build(   # This is the code line 89
    :user_id => @user.id
  )

  if @article.save
    ...
  end
end

我收到此错误

NoMethodError (undefined method `title' for #<Comments:0x00000103abfb90>):
  app/controllers/articles_controller.rb:89:in `create'

可能是因为所有Review“关联的”类\模型和Comment的验证运行没有 title属性。我认为,因为如果在插件代码中我注释掉了像这样的验证方法

module Article
  ...

  included do
    # validates :title,  # Validation
    #   :presence => true
  end

  ...
end

我不再有错误了。

那么,我该如何解决这个问题?

注意:我不是创建插件的专家(这是我的第一次),所以我也暗中问我是否为插件实现做得很好......

1 个答案:

答案 0 :(得分:2)

您在ActiveRecord :: Base中包含 validates_presence_of:title ,因此每个活动记录模型都会提取它。相反,你应该这样做:

# vendor/plugins/article/lib/acts_as_article.rb
module Article
  extend ActiveSupport::Concern

   module ClassMethods
    def acts_as_article
      validates :title,  # Add validation method here
        :presence => true
      send :include, InstanceMethods
    end
  end

  module InstanceMethods
    ...
  end
end

因此,您只需要在ActiveRecord模型上包含期望验证通过的验证。如果这解决了您的问题,请告诉我。