新手问题 请教大大为什么有时候 active record 里面 count 中有数字,但实际查询出来没有内容

physaris · 2019年10月30日 · 最后由 physaris 回复于 2019年10月30日 · 2247 次阅读

请教大大,下面代码是不是写的不对,注释的地方标出了问题。

数据库是 sqlite3,框架是 rails 3.2.22,ruby 版本是 2.1.10

感谢!

destruction_item1s.delete_all
kases.each do |kase|
    # DestructionItem1.transaction do
        kase.kase_item1s.each do |kase_item1|
            found = false
            logger.debug(destruction_item1s.count)                # 这一行count是有数字的  <-------------
            byebug
            # 但下面的这个循环并不会被执行,因为destruction_item1s = [],是空的  <-------------
            destruction_item1s.each do |destruction_item1|
                if kase_item1.product_id == destruction_item1.product_id
                    destruction_item1.amount += kase_item1.amount
                    found = true
                end
            end
            if !found
                DestructionItem1.create(
                    destruction_id: id,
                    category_id: kase_item1.category_id,
                    product_id: kase_item1.product_id,
                    name: kase_item1.name,
                    spec: kase_item1.spec,
                    bottles_per_box: kase_item1.bottles_per_box,
                    amount: kase_item1.amount,
                    amount_box: kase_item1.amount_box,
                    price_supply: kase_item1.price_supply,
                    price_market: kase_item1.price_market,
                )
            end
        end
    # end
end

count 出来的数字不是 0 吗?

ken 回复

第一次循环是 0,第二次是 1,这个数字会因为下面的 create 增加个数,但是 destruction_item1s 这个 has_many 关系出来的结果是空 [],挺奇怪的不知道错在哪里。

physaris 回复

destruction_item1s .each改成destruction_item1s .reload.each 应该就不为空了

count可能直接执行了 sql,所以查到的是数据库的数据。

以上是瞎猜。

ken 回复

嗯,确实是你说的这样,我一直不知道 reload 这个方法,试了 nocache 什么的都不行,多谢了!!👍

physaris 关闭了讨论。 10月30日 17:30
需要 登录 后方可回复, 如果你还没有账号请 注册新账号