Rails multi-model form with data having a Hash containing a Hash
I'm faced with the following problem in rails. I have a form to edit/create a new project that may contain 1 to n sub-projects that again can contain 1 to n tasks.
So when I create a new project the controller executes:开发者_如何学JAVA
@project = Project.new
sub_project = SubProject.new
work = Work.new
sub_project.works << work
@project.sub_projects << sub_project
Having the basic structure I generate the input fields in the view, the form I build up like this:
Project
<% form_for (:project, :url => action_parameter, :id => project) do |form| %>
Subproject
<% fields_for "project[sub_projects][]", sub_project do |subproject_form| %>
Up to here all went well but how do I now define the fields_for the tasks? The following attempt..
<% fields_for "project[sub_projects][works][]", work do |work_form| %>
.. is not the solution as I get the following error from Mongrel:
Conflicting types for parameter containers. Expected an instance of Hash, but found an instance of Array. This can be caused by passing Array and Hash based paramters qs[]=value&qs[key]=value.
Why doesn't this work? And how should I tackle my problem?
You need to use a nested model form. Check out this web cast from Ryan Bates.
The reason why my code didn't work was that I forgot to add some extra braces in the work line..
<% fields_for "project[sub_projects][][works][]", work do |work_form| %>
However what I attempted to do does not seem possible with pre Rails 2.3.X. So I updated my App to that version and then used the nested forms which John Drummond suggested.
精彩评论