Rails after_save回调没有触发

时间:2014-12-23 23:15:52

标签: ruby-on-rails callback rails-activerecord after-save

我有下面的代码可以正常删除记录,但是在尝试使用after_save回调将记录插入表中时,什么都不做。

基本上我正在做的是创建一系列高级关系,这些关系应该从表campaign_category_metro_bids创建或删除关系。如果我在PHPMyAdmin中运行就没有问题。但是单击并激活rails只允许第二个回调,after_destroy被调用...

 class CampaignMetro < ActiveRecord::Base

    belongs_to :campaign
    belongs_to :metro

    after_destroy :destroy_category_campaign_metro_bid
    after_save    :create_category_campaign_metro_bid

    def create_category_campaign_metro_bid
        insert = "INSERT INTO campaign_category_metro_bids (campaign_id,category_id, metro_id, created_at, updated_at)
                    SELECT e.campaign_id, e.category_id, e.metro_id, NOW(), NOW()
                    FROM
                    (SELECT c.campaign_id, c.category_id, c.metro_id
                     FROM (SELECT a.campaign_id, a.category_id, b.metro_id
                           FROM campaign_categories a 
                           cross join campaign_metros b 
                           ON a.campaign_id = b.campaign_id) c) e
                    LEFT JOIN campaign_category_metro_bids d
                    ON d.campaign_id = e.campaign_id and
                       d.category_id = e.category_id and
                       d.metro_id    = e.metro_id
                    WHERE d.campaign_id is null and 
                          d.category_id is null and 
                          d.metro_id    is null;"

        ActiveRecord::Base.connection.execute(insert)
    end

    def destroy_category_campaign_metro_bid
        delete="DELETE d.*
                FROM campaign_category_metro_bids d
                LEFT JOIN
                (SELECT c.campaign_id, c.category_id, c.metro_id
                 FROM (SELECT a.campaign_id, a.category_id, b.metro_id
                       FROM campaign_categories a 
                       cross join campaign_metros b 
                       ON a.campaign_id = b.campaign_id) c) e
                ON d.campaign_id = e.campaign_id and
                   d.category_id = e.category_id and
                   d.metro_id    = e.metro_id
                WHERE e.campaign_id is null and 
                      e.category_id is null and 
                      e.metro_id    is null;"

        ActiveRecord::Base.connection.execute(delete)
    end
end

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:1)

问题是在after_save上,将在数据库上创建记录的事务尚未提交,因此记录尚未真正存在。您必须使用after_commit

http://apidock.com/rails/ActiveRecord/Transactions/ClassMethods/after_commit