Skip to content

ActiveRecord::Persistence#touch should not use default_scope #1519

Closed
wants to merge 2 commits into from

3 participants

@dmitriy-kiriyenko

Hi.

Using update_all in touch looks smart enough, but there is a hidden issue in this: update_all uses default_scope.

Imagine a situation: you have the following User class:

class User < ActiveRecord::Base
  default_scope :active => true
end

user = User.unscoped.where(:active => false).first

user.touch
# This fires sql "UPDATE `users` SET `updated_at` = ? WHERE `users`.`active` = 0"
# and so our user instance remains changed (and the database remains unchanged)
user.changed? #=> true
user.reload # brings old updated_at value back to life

I've provided a test proving that and a fix for the issue.

@josevalim
Ruby on Rails member

Great patch. Could you just please tell which Rails version this is happening? /cc @jonleighton @tenderlove

@dmitriy-kiriyenko

This is happening in edge (master) and 3.0.7, that I am using currently.
In 3.0.7 there is also additional similar issue: if there is a default_scope joins(:association), update_all produces sql like:
UPDATE `base_table_name` SET `updated_at` = ? WHERE `id` = ? JOIN `association_table_name` ON ...
and results in error "column updated_at is ambiguous". However, this particular bug not found in edge.

I'd say that this happens since e4943e9 where current touch implementation was introduced, but I've tested only in 3.0.7 and master.

@jonleighton
Ruby on Rails member

I have merged this, thanks!

@jonleighton jonleighton closed this Jun 7, 2011
@jonleighton
Ruby on Rails member

Incidentally, ActiveRecord::Relation has never supported joins on updates, which is the root cause of the error on 3-0-stable you describe. I plan to fix this for 3.2.

@porras porras added a commit to porras/rails that referenced this pull request Sep 7, 2011
@porras porras Update changelog for 'Backport "ActiveRecord::Persistence#touch shoul…
…d not use default_scope" (pull request #1519)'
5ae76c4
@jonleighton jonleighton added a commit that referenced this pull request Sep 7, 2011
@porras porras Update changelog for 'Backport "ActiveRecord::Persistence#touch shoul…
…d not use default_scope" (pull request #1519)'
de178df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.