diff --git a/app/controllers/administrate/application_controller.rb b/app/controllers/administrate/application_controller.rb index 1b4dc3d5de..52f182ffee 100644 --- a/app/controllers/administrate/application_controller.rb +++ b/app/controllers/administrate/application_controller.rb @@ -44,6 +44,7 @@ def create authorize_resource(resource) if resource.save + yield(resource) if block_given? redirect_to( after_resource_created_path(resource), notice: translate_with_resource("create.success"), diff --git a/docs/customizing_controller_actions.md b/docs/customizing_controller_actions.md index f9fedad26e..73d98ca1e6 100644 --- a/docs/customizing_controller_actions.md +++ b/docs/customizing_controller_actions.md @@ -93,3 +93,17 @@ To set custom redirects after the actions `create`, `update` and `destroy` you c [namespace, requested_resource.some_other_resource] end ``` + +## Creating Records + +You can perform actions after creation by passing a `block` to `super` in the +`create` method. The block will only be called if the resource is successfully +created. + +```ruby +def create + super do |resource| + # do something with the newly created resource + end +end +``` diff --git a/spec/controllers/admin/application_controller_spec.rb b/spec/controllers/admin/application_controller_spec.rb index 06b99543fd..82900a1e24 100644 --- a/spec/controllers/admin/application_controller_spec.rb +++ b/spec/controllers/admin/application_controller_spec.rb @@ -46,6 +46,33 @@ def after_resource_updated_path(requested_resource) end end + describe "creation yeilds resource" do + controller(Admin::OrdersController) do + attr_reader :resource + + def create + super do |resource| + @resource = resource + end + end + end + + it "yields the created resource after creation" do + customer = create(:customer) + order_attributes = build(:order, customer: customer).attributes + params = order_attributes.except( + "id", + "created_at", + "updated_at", + "shipped_at", + ) + + post :create, params: { order: params } + + expect(controller.resource).to be_a(Order) + end + end + describe "authorization" do controller(Administrate::ApplicationController) do def resource_class