You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Devise按子域名(:account)登录作用域配置报错求助

Fixing "undefined method `account' for ActionDispatch::Request" with Devise + Apartment Multi-Tenancy

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 User records have the correct account values matching the subdomains you want to use.

内容的提问来源于stack exchange,提问作者Jeremy Bray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:25:26