Rails 3:Model.all.count 在 after_create 方法中总是返回 1 [英] Rails 3: Model.all.count always returns 1 in after_create method

查看:31
本文介绍了Rails 3:Model.all.count 在 after_create 方法中总是返回 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果新创建的记录是第一个满足某些条件的记录,我想检查 after_create.所以我希望能够检查, Model.where(...some condition...).count >1,在 after_create 回调中.但是,Rails 出于某种原因不允许这样做,我找不到任何解释原因.如果我查询Model.all.count,在after_create中,它总是返回1,而1条记录就是我刚刚创建的那条记录.如果我在 after_create 方法中执行原始 SQL,那么我可以检索正确的信息.为什么我不能使用 Model.where(...) 执行查询?

I want to check in after_create if the newly created record is the first one that meets some condition. So I want to be able to check, Model.where(...some condition...).count > 1, in an after_create callback. However, Rails will not allow this for some reason and I can't find any explanations why. If I query, Model.all.count, in after_create, it always returns 1, and the one record is the one I just created. If I execute raw SQL in the after_create method then I can retrieve the correct information. Why can't I perform the query using Model.where(...)?

回答以下问题.没有错误消息.下面是记录输出的类和示例.我觉得这一定是我忽略了一些愚蠢的事情,感谢您的帮助.

In response to questions below. There are no errors messages. Below is the class and an example of the logged output. I feel like it must be something stupid I'm overlooking, I appreciate the help.

class ExperiencePhoto < ActiveRecord::Base
  belongs_to :experience, counter_cache: true
  belongs_to :photo


  after_create :set_cover_photo

  def self.find_or_create(params)
    where(params).first_or_create
  end


  protected

  def set_cover_photo
    logger.debug self.inspect
    logger.debug ExperiencePhoto.all.inspect
    logger.debug ExperiencePhoto.all.count.to_s
    logger.debug ActiveRecord::Base.connection.execute("select count(*) from experience_photos")[0].inspect

  end

结束

调用:

ExperiencePhoto.find_or_create(photo_id: photo_id, experience_id: self.id)

导致此输出:

#<ExperiencePhoto id: 183, experience_id: 93, photo_id: 106>
[#<ExperiencePhoto id: 183, experience_id: 93, photo_id: 106>]
1
{"count"=>"168"}

推荐答案

ExperiencePhoto.all.count 的日志显示什么 SQL?

What SQL does the log show for ExperiencePhoto.all.count ?

我不确定,但我猜是因为 set_cover_photo 是在前面的 where 的范围内调用的.

I don't know for sure, but I would guess it's because set_cover_photo is called with the scope of the previous where.

尝试将其包装在 unscoped 中:

Try wrapping it in unscoped:

def set_cover_photo
  ExperiencePhoto.unscoped do
    logger.debug self.inspect
    logger.debug ExperiencePhoto.all.inspect
    logger.debug ExperiencePhoto.all.count.to_s
    logger.debug ActiveRecord::Base.connection.execute("select count(*) from experience_photos")[0].inspect
  end
end

这篇关于Rails 3:Model.all.count 在 after_create 方法中总是返回 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆