Recently I was faced with the task of validating a model with a HABTM relationship. I tried looking around for various solutions but all of them seemed quite complicated and time consuming to implement until I came across this nifty solution. Lets say you have two models - posts and tags with a HABTM relationship.
You probably already have the relationship defined in your model, if not, it goes something like this:
Now in addition to that, just go ahead and add multiple validation rule in your post model:
And last but not least add a beforeValidate filter …
All you have to do now is add the following snippet in your main model’s controller:
That will check for the errors raised in the main model’s validationErrors and copies them back to the HABTM’s model so that the view can correctly capture and print that validation error.