bezzoon
bezzoon

Reputation: 2019

Rails resource - calling a method after edit form is submitted

The edit form works perfectly. I want to call a method after editing a profile [to notify us that it has been edited]. What is the correct way of doing that?

route

there are a lot more routes but.. I am not sure they are necessary info

  resources :profiles

..

controller

  # GET /profiles/1/edit
  def edit
  end

  def call_this_after_edit_is_clicked
    ...
  end

Upvotes: 0

Views: 707

Answers (1)

James Mason
James Mason

Reputation: 4296

There are three ways to do this (and an extra-credit fourth):

Call your method at the end of your action. This is simple, but it does clutter your controller action a bit.

def update
  #... do stuff ...
  call_this_after_edit_is_clicked
end

Use an after action. This is handy if you need to call this method after several controller actions.

after_action :call_this_after_edit_is_clicked, only: :update

Move the code to the model with an after_update callback. This makes the code run any time the model is updated, not just when this particular controller is used to update it. This may or may not be what you want.

class ModelClass < ActiveRecord::Base
  after_update :call_this_after_edit_is_clicked

  # ... other stuff ...
end

For extra credit, use one of the first three to schedule your code as background task using Resque (or Delayed Job or similar). This is the route you want to go if your extra method is going to do something slow. If you're sending a notification email or updating a bunch of flags in your database, do this.

Upvotes: 2

Related Questions