开发者

Rails Form Validations for Multi-Model Forms

I am trying to build a Rails app with multiple models in a single form, and multiple forms on a single page. To make that work (according to my limited knowledge), I have to drop out of the scaffold code and the "form_for :model" helper and use "form_tag" instead. However when I do that, I lose the ability to automatically ca开发者_如何学Pythontch and report form validation errors in the view (with the error message in the flash[:error] and have the invalid fields highlighted.

If I have a controller method for a form that has to validate data from multiple models, how to I pass the validation errors back to the form? What do I have to do to get the invalid fields highlighted?

(For the longest time I didn't "get" Rails forms, because I thought they were useless Ruby wrappers for HTML code. Now that I am working in a non-Rails environment, I realize how much hard work they save because validation is tied to ActiveRecord validaions, and if a validation fails, the form can be reposted with the invalid fields hightlighted and a useful message in flash[:error]).


To add multiples models to a simple form, after rails 2.3 you just have to add accepts_nested_attributes_for in your model, the model that will be connected with your controllers and views, change the views to support information from another models (with field_for) and maybe build the reference objects in your controllers. Check these links:

  • http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes.
  • http://github.com/alloy/complex-form-examples
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜