开发者

Apply validation to single object only - Rails 3

开发者 https://www.devze.com 2023-01-17 11:24 出处:网络
Lets say I\'ve Comment class that is polymorphic and I use it in many places within a system. class Comment < ActiveRecord::Base

Lets say I've Comment class that is polymorphic and I use it in many places within a system.

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

And there is this one place in which I would like to apply validation on Comment's content length. How should I approach this problem?

1) Use STI and add new validation in subclass - I feel it is an overkill 2) Extend this single object being created/updated within controlle开发者_Python百科r with validation required. But how to achieve it without permanently extending its class?


You can try to do this (Rails 2.3 style as I haven't given a try to Rails 3 yet but I suppose the solution is quite similar):

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
  attr_accessor :content

  attr_accessor :should_validate_comment_length

  validates_length_of :content, :maximum => 100, :if => :should_validate_comment_length
end

Then in the place where the validation should be active you can do:

def create
   @comment = #somehow obtain a comment model instance (like from POST)
   @comment.should_validate_comment_length = true
   if @comment.valid?
      ...
end

Hope it will help

0

精彩评论

暂无评论...
验证码 换一张
取 消