Alexander Gorg
Alexander Gorg

Reputation: 1078

What to use instead of after_commit in controller in Rails 5?

Today I tried to use a wonderful callback :after_commit which triggers when the object is written to database, however, I've got the error message from Rails:

ActionController::RoutingError (undefined method `after_commit' for ImagesController:Class
Did you mean?  after_action):

Well, that was embarassing! And it seems like this callback was deprecated! Looking through search, I tried to use :after_create_commit, which gave me the same error.

The third step was to try :after_action. Here goes the question: How to make it work the same way as :after_commit?

I've already tried apidock.com - it's really minimal! Also I've tried api.rubyonrails.org - it is saying about blocks, but I'm not a ruby ninja to understand it. So I really apprecite if you could spill some light on it!

ImagesController:

class ImagesController < ApplicationController
  after_create_commit :take_image_to_album

  def take_image_to_album
    if check_album
      add_inner_to_album(@image)
    end
  end

  def create
    @image = Image.create(image_params.merge(:user_id => current_user.id)

    respond_to do |format|
      unless @image.save
        format.html { render :show, notice: "Error!" }
        format.json { render json: @image.errors, status: :unprocessable_entity }
      else
        format.html
        format.json { render :show, status: :ok, location: @image }
      end
    end
  end
  ...

  def add_inner_to_album(image)
    contents = @album.content
    contents << [image.id, image[:imageup], false]
    @album.update(:content => contents)
  end
  end

Upvotes: 1

Views: 1947

Answers (1)

MatayoshiMariano
MatayoshiMariano

Reputation: 2116

The after_commit method is only for models. In the controllers family, you have after_action, that will be executed after the action of the controller is finished.

For example, the after_action in a controller works like this:

class UsersController < ApplicationController
  after_action :log_activity, only: :show

  # GET v3/users/:id
  def show
    render status: :ok,
           json: { id: current_user.id, name: current_user.name }
  end

  def log_activity
    current_user.update(last_activity_at: Time.current)
  end

end

The log_activity method is executed after responding the request.

In the after_action :log_activity, only: :show, with only you can specify after which actions log_activity will run. If you do not specify any, it will run after every action defined in the controller.

Upvotes: 7

Related Questions