I have a model (let's call it Blog). It looks like:
class Blog < ApplicationRecord
belongs_to :author
def self.foo_all
all.each(&:bar)
end
def bar
author.baz
end
end
Now, the problem I'm having is that when author.blogs.foo_all method is called, it seems that the Blog class has a current_scope! This means that when inside the author.baz method, any query on Blog has the author as a scope on the query (WHERE authors.id == 123)!
Using an example where
- blog.id == 123
- author.id == 456
this is what happens:
Class Author < ApplicationRecord
has_many :blogs
def baz
id # 456
blogs.count # "SELECT count(*) FROM blogs WHERE blogs.author_id == 456"
Blog.count # "SELECT count(*) FROM blogs WHERE blogs.author_id == 456"
Blog.current_scope # "[Blog id: 123, author_id: 456]"
end
end
Yes, I can work around this why explicitly removing that scope, but it's SO unexpected! In what world does Blog.count not perform an unscoped query?!
Note: I do not use a default_scope anywhere.
Rails: 6.1.3.2
Copy of code with rspec test that replicates the problem https://github.com/hrdwdmrbl/StockOverflow69020511