2010-07-10 32 views

回答

3

類名是在以下設置爲實例的_type柱:

class Comment 
    belongs_to :commentable, :polymorphic => true 
end 

class Post 
    has_many :comments, :as => :commentable 
end 

評論類將有commentable_idcommentable_type領域。 commentable_type是類名,commentable_id是外鍵。如果通過特定的後留言評論要到驗證,你可以做這樣的事情:

validate :post_comments_are_long_enough 

def post_comments_are_long_enough 
    if self.commentable_type == "Post" && self.body.size < 10 
    @errors.add_to_base "Comment should be 10 characters" 
    end 
end 

OR,我覺得這個比較好:

validates_length_of :body, :mimimum => 10, :if => :is_post? 

def is_post? 
    self.commentable_type == "Post" 
end 

如果你有幾個驗證,我會推薦以下語法:

with_options :if => :is_post? do |o| 
    o.validates_length_of :body, :minimum => 10 
    o.validates_length_of :body, :maximum => 100 
end 
+0

這是低劣的部分。無法從多態模型中訪問屬性。 「未定義的方法'itemable_type'爲#」 – BlackTea 2010-07-10 13:44:16

+0

生活將是完美的,否則...... :( – BlackTea 2010-07-10 13:50:13

+0

如果您將上面的代碼直接寫入您的課程將會失敗,它只能用於實例,而不是類。將'define_method'代碼添加到實例方法中,並且它應該通過。 – 2010-07-10 14:53:50

1

validates_associated方法是你所需要的。 您只需將此方法鏈接到多態模型,它將檢查相關模型是否有效。

class Comment < ActiveRecord::Base 
    belongs_to :commentable, :polymorphic => true 
    validates_associated :commentable 
end 

class Post < ActiveRecord::Base 
    has_many :comments, as: commentable 

    validates_length_of :body, :minimum => 10 
    validates_length_of :body, :maximum => 100 
end 
+0

我得到這個錯誤undefined method'body 'for – 2017-11-08 17:05:39

+0

@KickButtowski也許是因爲你的模型沒有屬性'body'? – Guillaume 2017-11-29 16:27:06