Rails ポリモーフィック モデルがあり、関連するクラスに応じてさまざまな検証を適用したいと考えています。
1193 次
2 に答える
3
クラス名は、_type
たとえば次の設定の列にあります。
class Comment
belongs_to :commentable, :polymorphic => true
end
class Post
has_many :comments, :as => :commentable
end
コメント クラスにはcommentable_id
andcommentable_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
または、私はこれが好きだと思います:
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
于 2010-07-10T13:36:35.863 に答える