2010-07-10 50 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