2017-08-08 7 views
0

今日は素敵なコールバックを使用しようとしました:Rails 5のコントローラでafter_commitの代わりに使用するものは何ですか?

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

まあ、恥ずかしいた:オブジェクトがデータベースに書き込まれたときにトリガされafter_commitは、しかし、私はRailsのからのエラーメッセージを持っています!そして、このコールバックは廃止されたようです! 検索を見て、私は使用しようとしました:after_create_commit、私に同じエラーを与えた。 after_actionを:

第3のステップは試してみました。ここで質問になる: それは同じように動作するようにする方法:after_commit?

私は既にapidock.comを試しました。これは本当に最小です!また、私はapi.rubyonrails.orgを試しました - それはブロックについて言いますが、私はそれを理解するルビー忍者ではありません。だから、もしあなたがそれに光をあてることができたら、本当に感謝しています!

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 
+0

ImagesControllerには何がありますか? –

+0

'after_commit'はモデルにのみ適用されます。コントローラについては、 'after_action'を意味します。コントローラとモデルは共通の設計言語を共有しますが、必ずしもメソッド名である必要はありません。 – tadman

+0

@tadmanこのコールバックとそれに属するメソッドをモデルに移動するとしますか? –

答えて

6

after_commit方法が唯一のモデルです。コントローラファミリでは、コントローラの動作が完了した後に実行されるafter_actionがあります。

は、例えば、コントローラでafter_actionは次のように動作:

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 

log_activity方法は、要求を応答した後に実行されます。

after_action :log_activity, only: :showでは、onlyで、log_activityのアクションを実行することができます。 anyを指定しないと、コントローラで定義されたすべてのアクションの後に実行されます。

+0

"show_serializer"メソッドの目的は何ですか? –

+0

申し訳ありませんが、 'show_serializer'は返されるハッシュを返す責任しか持たないシリアライザクラスのインスタンスです。私は何かのためにそれを簡単に変更します – MatayoshiMariano

+0

ありがとうございました! –

関連する問題