I have been watching the last three episodes on railscasts.com in
which he goes through dealing with multiple models in one for using
fields_for, and virtual attributes. (Ruby on Rails Screencasts - RailsCasts
73). Here is an example of the way they suggest to go about it:
projects_controller.rb
def new @project = Project.new
3.times { @project.tasks.build }
end
def create @project = Project.new(params[:project])
if @project.save
flash[:notice] = “Successfully created project.”
redirect_to projects_path
else
render :action => ‘new’
end
end
models/project.rb
def task_attributes=(task_attributes)
task_attributes.each do |attributes|
tasks.build(attributes)
end
end
VIEW
<% form_for :project, :url => projects_path do |f| %>
Name: <%= f.text_field :name %>
<% for task in @project.tasks %>
<% fields_for "project[task_attributes][]", task do |task_form| %>
Task: <%= task_form.text_field :name %>
<% end %>
<% end %>
<%= submit_tag "Create Project" %>
<% end %>
This example uses a one to many relationship. (they go further in
future episodes, but for now this will be fine). My issue is that I
would like to do this over multiple relationships. For example: what
if a task had multiple requirements? How can I do this with still only
calling Project.new(params[:project]) and having everything still set
automatically?
My issue is that I
would like to do this over multiple relationships. For example: what
if a task had multiple requirements? How can I do this with still only
calling Project.new(params[:project]) and having everything still set
automatically?
I’m having a similar issue… I’m trying to use one form_for, and
MULTIPLE fields_for to set up nested models.
my models are like this (i’m omitting a bunch of stuff):
Post
:has_many :groups
Group
:has_many :post_items
I’ve got the second fields for looking something like this:
<% fields_for “post[group_attributes][][post_item_attributes][]”,
post_item do |post_item_form|%>
Link Text: <%= post_item_form.text_field :display_text %>
Alright, I think I have the issue figured out. In your example, i
think you have 1 too many sets of braces.
For the example above, if a task had multiple requirements, your view
would look something like the following for the requirements:
<% for requirement in @project.task.requirements %>
<% fields_for “project[task_attributes][requirement_attributes][]”,
requirement do |requirement_form| %>