#73 Complex Forms Part 1

Complex forms often lead to complex controllers, but that doesn't have to be the case. In this episode see how you can create multiple models through a single form while keeping the controller clean.
# 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

<!-- new.rhtml -->
<% form_for :project, :url => projects_path do |f| %>
  <p>
    Name: <%= f.text_field :name %>
  </p>
  <% for task in @project.tasks %>
    <% fields_for "project[task_attributes][]", task do |task_form| %>
      <p>
        Task: <%= task_form.text_field :name %>
      </p>
    <% end %>
  <% end %>
  <p><%= submit_tag "Create Project" %></p>
<% end %>

你可能感兴趣的:(F#,Flash)