# Include this module into the controllers you want to easy-mode CRUD
module AdminControllerCrudActions
COLUMN_MAP = {
:string => :text_field,
:text => :text_area,
:integer => :text_field,
:datetime => :datetime_select
}
def index
@collection = all
@model_class = current_model
render_inline_with_layout %{
<p><%= link_to "New", :action => "new" %></p>
<table>
<thead>
<tr>
<% @model_class.content_columns.each do |column| %>
<th><%= column.name.humanize %></th>
<% end %>
<th></th>
</tr>
</thead>
<tbody>
<% @collection.each do |instance| %>
<tr>
<% @model_class.content_columns.each do |column| %>
<td><%= instance[column.name] %></td>
<% end %>
<td>
<%= link_to "Edit", :action => "edit", :id => instance %>
<%= button_to "Destroy", {:action => "show", :id => instance}, :method => :delete, :confirm => "Are you sure?" %>
</td>
</tr>
<% end %>
</tbody>
</table>
}
end
def new
@instance = current_model.new
render_inline_with_layout(form_view)
end
def create
@instance = current_model.new(current_params)
if @instance.save
flash[:success] = "Saved successfully"
redirect_to :action => "index"
else
render :action => "new"
end
end
def edit
@instance = current_model.find(params[:id])
render_inline_with_layout(form_view)
end
def update
@instance = current_model.find(params[:id])
if @instance.update_attributes(current_params)
flash[:success] = "Saved successfully"
redirect_to :action => "index"
else
render :action => "edit"
end
end
def destroy
@instance = current_model.find(params[:id])
@instance.destroy
flash[:success] = "Deleted successfully"
redirect_to :action => "index"
end
private
def form_view
%{
<% form_for([:admin, @instance], :html => {:multipart => true}) do |f| %>
<% f.object.class.content_columns.reject {|c| c.name =~ /updated_at|created_at/ }.each do |column| %>
<%= f.label column.name %>
<% if column.name =~ /file_name$/ %><%# paperclip %>
<%= f.file_field column.name[/(.*?)_file_name/, 1] %>
<% else %>
<%= f.send((AdminControllerCrudActions::COLUMN_MAP[column.type] || column.type), column.name) %>
<% end %>
<% end %>
<p><%= f.submit %> or <%= link_to "cancel", :action => "index" %>.</p>
<% end %>
}
end
def all
current_model.find(:all)
end
# Post
def current_model
controller_name.singularize.camelize.constantize
end
# params[:post]
def current_params
params[controller_name.singularize]
end
def render_inline_with_layout(view)
render :inline => view, :layout => true
end
end