Skip to content

Instantly share code, notes, and snippets.

@patrickberkeley
Created September 6, 2009 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patrickberkeley/181899 to your computer and use it in GitHub Desktop.
Save patrickberkeley/181899 to your computer and use it in GitHub Desktop.
Example of nested attributes from belongs_to side of association.
<% form_for @event do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<% f.fields_for :category do |category_form| %>
<%= category_form.label :name %>
<%= category_form.text_field :name %>
<%= category_form.text_field :color %>
<% unless category_form.object.new_record? %>
<%= category_form.check_box '_delete' %>
<%= category_form.label '_delete', 'Remove' %>
<% end %>
<% end %>
<p>
<%= f.label :start_at %><br />
<%= f.datetime_select :start_at %>
</p>
<p>
<%= f.label :end_at %><br />
<%= f.datetime_select :end_at %>
</p>
<p><%= f.submit "Submit" %></p>
<% end %>
class Category < ActiveRecord::Base
has_many :events
validates_presence_of :name
end
class Event < ActiveRecord::Base
belongs_to :category
accepts_nested_attributes_for :category, :reject_if => :all_blank, :allow_destroy => true
end
class EventsController < ApplicationController
def index
@events = Event.all
end
def show
@event = Event.find(params[:id])
end
def new
@event = Event.new
@event.build_category
end
def create
@event = Event.new(params[:event])
if @event.save
flash[:notice] = "Successfully created event."
redirect_to @event
else
render :action => 'new'
end
end
def edit
@event = Event.find(params[:id])
end
def update
@event = Event.find(params[:id])
if @event.update_attributes(params[:event])
flash[:notice] = "Successfully updated event."
redirect_to @event
else
render :action => 'edit'
end
end
def destroy
@event = Event.find(params[:id])
@event.destroy
flash[:notice] = "Successfully destroyed event."
redirect_to events_url
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment