0

在我的控制器上的创建操作中,我使用 sql 查询来插入父记录和所有子记录。但它不会触发我需要的 after_save 回调。有没有一种干净的方法来触发这个?我尝试显式调用@record.save,但这会减慢表单的提交速度。谢谢

编辑1:添加相关模型/控制器代码

模型

after_save { do_some_stuff }

控制器

def create
  insert_query = "SELECT fn_insert_order_all('#{param1}', '#{param2}', '#{param3}', #{param4});"
  new_record = ActiveRecord::Base.connection.execute(insert_query)

  respond_to do |format|
    if new_record[0]["fn_insert_order_all"] != false
      @record = Order.find_by_id((new_record[0]["fn_insert_order_all"]).to_i)
      # @record.save # I can trigger the after_save callback here, but it results in slower performance
      format.json { render json: @record, status: :created }
    else
      error = { message: "record not saved" }
      format.json { render json: error, status: :unprocessable_entity }
    end
  end
end
4

1 回答 1

0

check in your model if you call after_create instead of after_save.

In the model the call to the triggered method should be something like:

after_create :your_func

In a model with a trigger I have working it looks like this:

class Mymodel < ActiveRecord::Base
    {attributes}
    after_create :your_func
        private
            def your_func
                {do the stuff}
            end
end

I hope that helps :)

于 2013-04-19T17:56:52.370 回答