Let me give a follow up example with a more simplified example…
Take a case where you have a “Person” model and a Person can have
several “Address” model objects.
You present a simple Person form and you provide fields of “address1”
and “address2” just as a starting point.
When the form submits you want to make sure the Address objects
validate correctly. (CRUD for the stuff I have working just fine.)
I’d like to keep validations on the Address object. For example…
class Address < ActiveRecord::Base
validates_numericality_of :zip_code (yes I know a validation
would be more than that for a zip code, but just as an example.)
Now in …
class Person < ActiveRecord::Base
addresses.each do | address |
#??? 2 ???
in 2 above, how do I collect errors from the Address object that can
utilize the validation rules already established on Address. For
example, shouldn’t there be a way I could leverage the
“validates_numericality_of” that is already defined on Address?
Of course in my Person model I could add ‘validates_associated
:addresses’ but that doesn’t work since the resulting error messages
are now all generic looking with just “Addresses is invalid” for each
failed validation on Address. I don’t want to duplicate validation
code (stay DRY), so I’m wondering what the best practice is. In theory
Address should be able to take care of its own way of validating
itself since you never know when it will need it to be validated
stand-alone (not part of a Person model.) Is the best practice to
create a more verbose validation method on the Address object and call
that as you iterate over addresses in person ? Should I just create
an Address model method:
#can I now call validate:
I was thinking in the above I could then maybe manually call…
validate_numericality_of but that doesn’t seem to work
Thanks for any help. I guess what I’d like to see is a best practice
of doing things the ‘rails way’ of a code snippet of where the
validation would be placed so that things are DRY. I feel like I must
be missing something obvious since I can’t see how this doesn’t come
up more in real life.
(Original post below…)
On Wed, Sep 3, 2008 at 11:05 PM, Rick [email protected] wrote:
Each “Match” also contains a collection (two) “PlayerGame” model
call them… even if manually… .from the Match controller. Using
“validates_associated :player_games” in my Match model ‘sort of’
works, but the resulting display messages are all wrong… you only end
up with a generic message “Player games is invalid” for each invalid
Are there some examples of what I need to do?
Thanks for any help.