3

我有下面的代码可以很好地删除记录,但是在尝试使用 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

我怎样才能让它工作?

4

1 回答 1

2

问题是after_save在数据库上创建记录的事务还没有提交,所以记录还没有真正存在。你必须使用after_commit.

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

于 2014-12-23T23:53:42.923 回答