开发者

Rails 2.3.5: How does one add an error when it doesn't make sense to put it in a validation?

I recently was trying to add errors.add_to_base code in the middle of some model logic and was wondering why it wasn't showing up in my view that was iterating over all errors. I then ran across this e-mail which expla开发者_运维技巧ins why: http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/e045ec1dead1ff06?pli=1

The question is then, how does one add errors with add_to_base if it doesn't make sense to put them into a validate method? I have some complex logic. The model needs to talk to a has_many relationship which has its own relationships that go through a myriad of conditionals to figure out if a request makes sense. It's nothing that can be tied to a validate method easily.

The one thing that I can do is create an instance variable and push all errors as strings to it while I iterate through my complex logic. After that I can run validate against the array and push those errors to the base object. Seems kind of lame though and not the Rails way of doing things.

Is the bottom line in the Rails community that complex logic, even when the logic spans multiple models, has to be in one particular models validate method? How is it handled when the validation is entirely complex and can span multiple models?


I don't understand why it doesn't make sense to put it into validations. For sure this what you want to do should be in a model, so you have to put it in some method inside the model. Then just add:

validate :my_method

and that's all. Of course if my_method gets too complicated, then split it in some logical sub methods.

If you have many related objects then you should put all validations that belongs to that objects in that objects models and when you try to save "parent" object, "child" objects will be also validated with their validations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜