插件中的验证方法 [英] Validation methods in plugins
问题描述
我正在使用Ruby on Rails 3.0.7,并且正在尝试为我的应用程序实现act_as_article
插件.我要做的是在该插件内为充当文章类"运行 validation 方法(请注意:我的插件需要创建一些数据库表列才能工作-其中一个表示为title
属性).
I am using Ruby on Rails 3.0.7 and I am trying to implement an act_as_article
plugin for my application. What I would to do is run validation methods for the "acting as article class" inside that plugin (note: my plugin requires to create some database table columns in order to work - one of these is represented by the title
attribute).
在我的RoR应用程序中,我有以下代码:
In my RoR application I have this code:
# 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
类中添加如下的 Record Association :
Using the above code the plugin works. However if I add some Record Association in the Review
class like this:
class Review
acts_as_article
has_many :comments # Adding association
...
end
,然后在我的ReviewsController
中添加以下内容:
and in my ReviewsController
I add the following, as well:
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
类没有 属性运行了验证.我认为这是因为,如果在插件代码中,我会注释掉这样的验证方法
Probably it happens because the validation run for all Review
"associated" classes\models and the Comment
class doesn't have the title
attribute. I think that because if inside the plugin code I comment out the validation method like this
module Article
...
included do
# validates :title, # Validation
# :presence => true
end
...
end
我再也没有错误.
那么,我该如何解决此问题?
注意:我不是创建插件的专家(这是我第一次),所以我也隐式地询问我是否在插件实现方面做得很好...
Note: I am not expert on creating plugin (this is my first time), so I ask implicitly also if I'm doing a good job for the plugin implementation...
推荐答案
您在ActiveRecord :: Base中包括了 validates_presence_of:title ,因此每个活动记录模型都在使用它.相反,您应该这样做:
You are including validates_presence_of :title in ActiveRecord::Base, and thus every active record model is picking it up. Instead, you should do:
# 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模型上包括验证.让我知道这是否解决了您的问题.
So that you only include the validation on ActiveRecord models that expect the validation to go through. Let me know if this solves your issue.
这篇关于插件中的验证方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!