2011-07-02 27 views
4

我正在使用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 

我再也不會收到錯誤了。

那麼,我該如何解決這個問題?

:我不是創建插件專家(這是我的第一次),所以我想問也隱含地,如果我做的插件實現了良好的工作...

+0

也許這可能有所幫助:https://github.com/apneadiving/Google-Maps-for-Rails/blob/master/lib/gmaps4rails/acts_as_gmappable.rb – apneadiving

回答

2

你是包括validates_presence_of:標題在ActiveRecord :: Base中,因此每個活動記錄模型都在拾取它。相反,你應該這樣做:

# 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模型中包含驗證,期望驗證通過。讓我知道這是否解決了你的問題。

+0

是的,它解決了我的問題。 – Backo