Rails 5.2 ActiveSupport CurrentAttributes & Basecamp 3 Account ID URL Scheme Discussion
How do you end up testing this with Minitest?
All controllers actions fail because env["REQUEST_PATH"] is nil
All controllers actions fail because env["REQUEST_PATH"] is nil
NoMethodError: undefined method split' for nil:NilClass
lib/account_middleware.rb:8:in
call'
Yeah, I'm wondering about this too.
Obviously there's a follow up episode which explains how to incorporate the middleware into System Tests, but there's presumably also a way have Integration Tests while using the account middleware.
Hi Chris,
This is great, but just wondering how I might be able to use an account_name rather than the account_id?
So would like the URL to look like: sample.com/coolaccount/posts/1
So I managed to get it mostly working using:
class AccountMiddleware def initialize(app) @app = app end def call(env) _, username, request_path = env["REQUEST_PATH"].split('/', 3) if username Current.user = User.where(username: username) env["SCRIPT_NAME"] = "/#{username}" env["PATH_INFO"] = "/#{request_path}" env["REQUEST_PATH"] = "/#{request_path}" env["REQUEST_URI"] = "/#{request_path}" end status, headers, body = @app.call(env) [status, headers, body] end end
The problem here, of course, is that I have a problem with URLs such as 'users/sign_up/' where Rails thinks username is 'sign_up'
What's the difference with this approach using middleware, and simply taking accounts out of the path in routes?
resources :accounts, path: '', except: [:index] do resources: projects end
(newbie question)
So how would you set the account_id
in the URL when a user logs in? surely its not as simple as just setting Current.account = user.account_id
?
You could do that initially. Although if you want to prevent users from hijacking the URL, you'll also need to protect your controllers by ensuring that the URL account_id
always matches the current_user
account ID. For example:
redirect_to root_path(script_name: "") unless current_user.account == Current.account