Skip to content

Instantly share code, notes, and snippets.

@lukesaunders
Created January 30, 2012 00:06
Show Gist options
  • Save lukesaunders/1701476 to your computer and use it in GitHub Desktop.
Save lukesaunders/1701476 to your computer and use it in GitHub Desktop.
Create multiple models at once using fields_for
<h1>Editing event</h1>
<%= twitter_bootstrap_form_for(@event) do |f| %>
<%= f.inputs "General" do %>
<%= render :partial => 'form', :locals => { :f => f } %>
<% end %>
<%= f.inputs "Jobs" do %>
<%= f.fields_for(:jobs, @new_jobs) do |jf| %>
<%= jf.hidden_field :name %>
<%= jf.text_field :expected_time, :add_on => :prepend do %>
<span class="add-on"><%= jf.object.name %></span>
<% end %>
<% end %>
<% end %>
<div class="actions">
<%= f.submit 'Edit event' %>
</div>
<% end %>
class Event < ActiveRecord::Base
has_many :jobs
accepts_nested_attributes_for :jobs
end
class EventsController < ApplicationController
...
def edit
@event = Event.find(params[:id])
unless @event.jobs_finalized?
@new_jobs = Job.template_jobs
end
end
def update
@event = Event.find(params[:id])
@event.attributes = params[:event]
if @event.save
if params[:event][:jobs_attributes]
@event.jobs_finalized = true
@event.save
end
flash[:notice] = 'Event was successfully updated'
redirect_to event_path(@event)
else
render :action => :edit
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment