0

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 controller with validation required. But how to achieve it without permanently extending its class?

3
  • 1
    Can you tell us more about 'this one place'? Commented Sep 23, 2010 at 8:06
  • Have you considered just using HTML :maxlength => n ? Commented Sep 23, 2010 at 13:22
  • 1
    @Trip, we should always check it in server side as some user may post values but not using your form... Commented Sep 24, 2010 at 17:23

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.