bundle exec rails g scaffold Item name:string price:integer
class ItemsController < ApplicationController
# GET /items
# GET /items.xml
def index
@items = Item.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @items }
end
end
# ----- CUT ------
# DELETE /items/1
# DELETE /items/1.xml
def destroy
@item = Item.find(params[:id])
@item.destroy
respond_to do |format|
format.html { redirect_to(items_url) }
format.xml { head :ok }
end
end
end
Untuk mengubahnya, menurut Jose Valim saat menjawab pertanyaan tentang scaffold controller dari ZigZag, cukup salin rails/railties/lib/generators/rails/scaffold_controller/templates (github link) ke RAILS_ROOT/lib/templates/rails/scaffold_controller/controller.rb
dan lakukan perubahaan sesuai kebutuhan. Contoh:
# RAILS_ROOT/lib/templates/rails/scaffold_controller/controller.rb
class <%= controller_class_name %>Controller < ApplicationController
before_filter :find_<%= file_name %>, :only => [:show, :edit, :update, :destroy]
<% unless options[:singleton] -%>
def index
@<%= table_name %> = <%= orm_class.all(class_name) %>
end
end
<% end -%>
def show
end
def new
@<%= file_name %> = <%= orm_class.build(class_name) %>
end
def edit
end
def create
@<%= file_name %> = <%= orm_class.build(class_name, "params[:#{file_name}]") %>
if @<%= orm_instance.save %>
redirect_to(@<%= file_name %>, :notice => "<%= human_name %> was successfully created.")
else
render :action => "new"
end
end
def update
if @<%= orm_instance.update_attributes("params[:#{file_name}]") %>
redirect_to(@<%= file_name %>, :notice => "<%= human_name %> was successfully updated.")
else
render :action => "edit"
end
end
def destroy
@<%= orm_instance.destroy %>
redirect_to(<%= table_name %>_url)
end
private
def find_<%= file_name %>
@<%= file_name %> = <%= orm_class.find(class_name, "params[:id]") %>
end
end
Jalankan scaffold, maka controller yang dihasilkan akan berubah. bundle exec rails g scaffold Post title:string content:string
0 comments:
Post a Comment