Img_0736_small James Miller 2 posts

Hey Ryan,

Another great screencast!

When using the built-in validation methods, is there any way to change the way that the entire error message is displayed? For example, the “Showings is invalid” is not a great message. Something like “One or more of your showings is invalid” would be more appropriate. Do we have to resort to custom + add_to_base to achieve this? How would you even accomplish a custom validation on associated records?

Also, with the future has_many :showings, :validate => true/false, does setting the value to true still not handle update actions?

Thanks,
James

 
Ryan_bates_cropped_small Ryan Bates 25 posts

Great questions! Regarding setting the full error message, there’s currently no easy way to do this. The problem stems from how Rails stores the error messages (basically in a hash). Until that changes I’m afraid most solutions will be fairly hackish.

One way is, as you mentioned, to make a custom add_to_base message. You could do that like so: (untested)


validate :showings_must_be_valid

def showings_must_be_valid
  unless showings.map(&:valid?).all? # all? is called later to ensure valid? is called on all showings
    errors.add_to_base "One or more of your showings is invalid" 
  end
end

Keep in mind that the other validation will still take place on creation until you can disable them in the next Rails update.

Another solution is to make your own version of the error_messages_for method and add a special case in there so that, when it comes to a “showings” validation error, it prints it out differently. Sorry I don’t have code for this.

There’s also a Rails plugin called Custom Error Messages which advertises this ability, but I haven’t tested it.

Also, with the future has_many :showings, :validate => true/false, does setting the value to true still not handle update actions?

I don’t believe so. From looking at the source it appears that setting it to true is the default behavior. It will only perform the association validation on creation. I personally prefer to disable association validation entirely and add it back manually. This way it’s more explicit, it’s easier to see what’s going on, and we can have more control in how it handles it.

2 posts, 2 voices