开发者

after_commit for rails controller

开发者 https://www.devze.com 2023-02-21 04:16 出处:网络
I know that an after_commit callback is provided for ActiveRecord objects in Rails 3.However, I would like to get access to this functionality in a Rails Controller.

I know that an after_commit callback is provided for ActiveRecord objects in Rails 3. However, I would like to get access to this functionality in a Rails Controller.

The intent is to do something like this in the controller:

rescue_from AccountError, :with => :render_internal_error

after_commit :render_created, :on =&开发者_如何学Gogt; :create

def create
  Account.transaction do
    modify_underlying_system
    @account.save!
  end
end

protected
def render_created
  render :status => 201, :json => {...}
end

def render_internal_error
  render :status => 500, :json => {...}
end

Is there some way I could achive this? I do not want to use the ActiveRecord after_commit callback, because it would mean breaking the separation between model and controller by having the model do rendering, which is something it should not be doing.


This should do what you're trying to do:

def create
  begin
    Account.transaction do
      modify_underlying_system
      @acount.save!
    end
    render :status => 201, :json => {...}
  rescue ActiveRecord::RecordInvalid
    render :status => 500, :json => {...}
  end
end

I didn't test it, but that looks about right.

0

精彩评论

暂无评论...
验证码 换一张
取 消