I’m trying to understand something basic about Rails (and Apache).
This is a follow-up to Matt Jones’ answer in Redirecting to Google Groups
I repeat his answer here
I suspect
User.exists?
is going to be the lightest possible option.User.count == 0
will also work, but I know there are some DBs where that operation can be expensive on large tables.
This is still going to do a query every time it checks, so if that’s too much load you could cache the result:
class User < ActiveRecord::Base
def self.any_users?
@any_users ||= exists?
end
end
Then your role-defaulting code can check
self.class.any_users?
, which will only run one query (per server) that returns true.
NOTE NOTE NOTE: the above is not 100% thread-safe. It assumes that there is exactly one user sending requests trying to be the first. If you’re worried about somebody racing to sign up for that first account, you’ll want to come up with a more secure approach.
–Matt Jones
In class User < ActiveRecord::Base
def self.any_users?
@any_users ||= exists?
end
end
``
So at some point in the code, I call User.any_users;
``
So Ruby says “Ok, @any_users isn’t defined so I’m going to call exists?” That makes perfect sense.
Let’s say I have several people banging on my website. Do each of them get a completely different copy of Rails? How many copies of @any_users are there? Does @any_users get initialized for each user? What data is common for all threads? What’s different for all threads?
Where can I learn more about this? I’ve skimmed How do I know whether my Rails app is thread-safe or not? - by Jarkko of Bear Metal but it really isn’t helping me understand what is and isn’t common between each thread/user/session.