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
精彩评论