From 339e4e80d514bd94fcb0e15689db43e5de83642a Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Fri, 7 Dec 2012 20:37:25 +0100 Subject: Let the scaffold example use the "set shared record" pattern to explain callbacks --- .../rails/scaffold_controller/templates/controller.rb | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) (limited to 'railties/lib/rails/generators') diff --git a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb index d6bce40b0c..5fc4ab8f6c 100644 --- a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb +++ b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb @@ -4,6 +4,8 @@ require_dependency "<%= namespaced_file_path %>/application_controller" <% end -%> <% module_namespacing do -%> class <%= controller_class_name %>Controller < ApplicationController + before_action :set_<%= singular_table_name %>, except: [ :index, :new, :create ] + # GET <%= route_url %> # GET <%= route_url %>.json def index @@ -18,8 +20,6 @@ class <%= controller_class_name %>Controller < ApplicationController # GET <%= route_url %>/1 # GET <%= route_url %>/1.json def show - @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %> - respond_to do |format| format.html # show.html.erb format.json { render json: <%= "@#{singular_table_name}" %> } @@ -39,7 +39,6 @@ class <%= controller_class_name %>Controller < ApplicationController # GET <%= route_url %>/1/edit def edit - @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %> end # POST <%= route_url %> @@ -61,8 +60,6 @@ class <%= controller_class_name %>Controller < ApplicationController # PATCH/PUT <%= route_url %>/1 # PATCH/PUT <%= route_url %>/1.json def update - @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %> - respond_to do |format| if @<%= orm_instance.update_attributes("#{singular_table_name}_params") %> format.html { redirect_to @<%= singular_table_name %>, notice: <%= "'#{human_name} was successfully updated.'" %> } @@ -77,7 +74,6 @@ class <%= controller_class_name %>Controller < ApplicationController # DELETE <%= route_url %>/1 # DELETE <%= route_url %>/1.json def destroy - @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %> @<%= orm_instance.destroy %> respond_to do |format| @@ -86,7 +82,12 @@ class <%= controller_class_name %>Controller < ApplicationController end end + private + # Use callbacks to share common setup or constraints between actions. + def set_<%= singular_table_name %> + @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %> + end # Use this method to whitelist the permissible parameters. Example: params.require(:person).permit(:name, :age) # Also, you can specialize this method with per-user checking of permissible attributes. -- cgit v1.2.3