I’m having trouble understanding how singular resource works in Rails.
In particular, how does Rails know which singular belongs to me when I access a Rails app across a session; and how does the Rails app make sure there are no conflicts when there are many users?
Does the server somehow map requests (based on IP) to unique Rails processes? And each process correspond to a single IP and when a previously unknown IP connects a new Rails process starts?
If so, how is it possible that I can log in as multiple users (using different browsers) on the same machine?
And how is it possible that I can go into multiple sessions with multiple singular resources on localhost running Webrick, if webrick is single threaded?
Any explanation or link to resources that I can read is appreciated.
The only thing the singular resource does is changes the routes that Rails sets up. So it basically removes all the
:ids from your routes (and it drops theindexroute because it makes no sense for a singular resource and is now the same as theshowroute).Rails doesn’t do anything magical for singular resources, no. You need to take care of that in your app. You’ll generally do this by using the session to store an id. Your session maps a cookie that it sends to the browser to a session instance stored by Rails in either a file, the DB, or something like memcache, so multiple app processes on the server are all using a common session store.
So, for example – after a user logs in, you’ll store his
user_idin the session and you’ll have abefore_filterin the controller of your singular resource (and all other controllers that need it) that retrieves thatuser_idfrom the session and retrieves theUserrecord using standard ActiveRecord finders.If you want to log in as multiple users then you need some sort of scope/namespace identifier as well as the
user_id, but really it’d be best to use one of the authentication gems here – many of which have some sort of scope mechanism.