我正在使用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
我再也不會收到錯誤了。
那麼,我該如何解決這個問題?
注:我不是創建插件專家(這是我的第一次),所以我想問也隱含地,如果我做的插件實現了良好的工作...
也許這可能有所幫助:https://github.com/apneadiving/Google-Maps-for-Rails/blob/master/lib/gmaps4rails/acts_as_gmappable.rb – apneadiving