activerecord - Rails 3: Model.all.count always returns 1 in after_create method -
i want check in after_create if newly created record first 1 meets condition. want able check, model.where(...some condition...).count > 1, in after_create callback. however, rails not allow reason , can't find explanations why. if query, model.all.count, in after_create, returns 1, , 1 record 1 created. if execute raw sql in after_create method can retrieve correct information. why can't perform query using model.where(...)?
edit:
in response questions below. there no errors messages. below class , example of logged output. feel must stupid i'm overlooking, appreciate 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(*) experience_photos")[0].inspect end end
calling this:
experiencephoto.find_or_create(photo_id: photo_id, experience_id: self.id) results in output:
#<experiencephoto id: 183, experience_id: 93, photo_id: 106> [#<experiencephoto id: 183, experience_id: 93, photo_id: 106>] 1 {"count"=>"168"}
what sql log show experiencephoto.all.count ?
i don't know sure, guess it's because set_cover_photo called scope of previous where.
try wrapping in unscoped:
def set_cover_photo experiencephoto.unscoped logger.debug self.inspect logger.debug experiencephoto.all.inspect logger.debug experiencephoto.all.count.to_s logger.debug activerecord::base.connection.execute("select count(*) experience_photos")[0].inspect end end
Comments
Post a Comment