Validating a single attribute

Is there a handy way to run validation on a single attribute?

I have a form with potentially many objects. The user will enter a
single number for each of these objects and I’d like to perform
validation on that entry. But I don’t want to fully validate the object
because of the associations involved in running a full validation.

Jake J. wrote:

Is there a handy way to run validation on a single attribute?

I have a form with potentially many objects. The user will enter a
single number for each of these objects and I’d like to perform
validation on that entry. But I don’t want to fully validate the object
because of the associations involved in running a full validation.

Jake,
As written, your question begs a simple answer…which in this case is
‘Yes’.

It’s been my experience that I always get more/better help if I include
some code in my questions.

In this case, we don’t have any names with which to provide you with an
example of how it would be written. If you send along the schema for
your object and explain a bit more about how this object appears in your
form, then we can probably provide better help.

thanks,
jp

Jeff P. wrote:

Jake J. wrote:

Is there a handy way to run validation on a single attribute?

I have a form with potentially many objects. The user will enter a
single number for each of these objects and I’d like to perform
validation on that entry. But I don’t want to fully validate the object
because of the associations involved in running a full validation.

Jake,
As written, your question begs a simple answer…which in this case is
‘Yes’.

It’s been my experience that I always get more/better help if I include
some code in my questions.

In this case, we don’t have any names with which to provide you with an
example of how it would be written. If you send along the schema for
your object and explain a bit more about how this object appears in your
form, then we can probably provide better help.

thanks,
jp

Well, without adding too much detail, say I have:

validates_numericality_of :x
validates_associated :a
validates_associated :b
validates_associated :c

The a, b, c will be setup in advance so can be considered reliable. The
user will enter ‘x’ and that piece needs to be validated. I don’t want
to run validation on a, b, c because those make additional database hits
and have even more database hits when the associations’ associations are
validated in turn.

Ideally, I’d like something like:

obj.valid?(:only => :x)

What I’ve done for the time being is just write a method that sets a
variable, then I’ve modified my validations as such:

validates_associated :a, :if => !@validate_only_x
validates_associated :b, :if => !@validate_only_x
validates_associated :c, :if => !@validate_only_x

It’s not very pretty.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs