Devise按子域名(:account)登录作用域配置报错求助
Let's break down what's happening here and fix that error quickly.
The root of the problem is that you've told Devise to use :account as a request key, but ActionDispatch::Request doesn't have an account method built in. You're trying to scope logins by subdomain, so that account value should actually come from the request's subdomain—you just need to connect those dots properly.
Here are two straightforward solutions:
Solution 1: Use :subdomain directly as your request key
This is the simplest approach, since subdomain is already a built-in method on the request object. Update your User model like so:
class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, request_keys: [:subdomain] # Swap :account for :subdomain here def self.find_for_authentication(warden_conditions) # Map the subdomain value to your User's `account` field where(email: warden_conditions[:email], account: warden_conditions[:subdomain]).first end after_commit :create_tenant private def create_tenant # Add a check to avoid duplicate tenants if account.present? && !Apartment::Tenant.exists?(account) Apartment::Tenant.create(account) end end end
This way, Devise pulls the subdomain from the request automatically, and you just map it to your account database field in the authentication lookup.
Solution 2: Add an account method to the Request object
If you want to keep using :account as your request key (for clarity), you can extend the request object to return the subdomain when account is called. Create a new initializer file:
# config/initializers/request_extensions.rb ActionDispatch::Request.class_eval do def account subdomain # Return the request's subdomain as the "account" value end end
With this in place, your existing User model code (with request_keys: [:account]) will work, because request.account now returns the subdomain like you intended.
Quick Additional Checks
- Make sure users are accessing your app via the correct subdomain (e.g.,
myaccount.yourdomain.com) when logging in—this is where the subdomain/account value comes from. - Double-check that your
Userrecords have the correctaccountvalues matching the subdomains you want to use.
内容的提问来源于stack exchange,提问作者Jeremy Bray

