Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Yield created resource if block is given #2484

Merged
merged 1 commit into from
Jan 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/controllers/administrate/application_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
14 changes: 14 additions & 0 deletions docs/customizing_controller_actions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
27 changes: 27 additions & 0 deletions spec/controllers/admin/application_controller_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading