找不到名称“用户”的关联。它已经被定义了吗?嵌套属性 Rails 5

No association found for name `user'. Has it been defined yet? Nested Attributes Rails 5

构建一个 rails 5 应用程序,使用 devise 和 acts_as tennant。

不太确定哪里出错了,我正在尝试在 accounts/new 下以相同的形式创建帐户和帐户所有者。

目前我收到以下错误:

ArgumentError 在 /accounts/new 找不到名称“用户”的关联。已经定义了吗?

我检查了我的模型和控制器,但似乎无法弄清楚。

Account.rb

class Account < ApplicationRecord
  RESTRICTED_NAMES = ["www", "admin", "loadflo"]

  has_many :users

  before_validation :downcase_name, :create_account_name
  strip_attributes only: :account_name, regex: /[^[:alnum:]_-]/

  validates :user, presence: true
  validates :name, presence: true,
                   uniqueness: {case_sensitive: false},
                   exclusion: { in: RESTRICTED_NAMES, message: "This is a restricted name. Please try again or contact support." }

  accepts_nested_attributes_for :user

private

  def downcase_name
    self.name = name.try(:downcase)
  end

  def create_account_name
    self.account_name = self.name
  end

end

accounts_controller.rb

class AccountsController < ApplicationController
  before_action :set_account, only: [:show, :edit, :update, :destroy]

  def index
    @accounts = Account.all
  end

  def show

  end

  def new
    @account = Account.new
    @account.build_user
  end

  def edit

  end

  def create
    @account = Account.new(account_params)

    if @account.valid?
      @account.save
      flash[:success] = "Account created successfully."
      redirect_to new_user_session_path
    else
      render action: 'new'
    end
  end

  def update

  end

  def destroy

  end

private

  def account_params
    params.require(:account).permit(:name, user_attributes: [:email, :password, :password_confirmation, :first_name, :last_name, :mobile_tel])
  end

  def set_account
    @account = Account.find(params[:id])
  end

end

User.rb

class User < ApplicationRecord
  acts_as_tenant(:account)
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :confirmable, :trackable

end

我还在我的用户 table 上设置了 account_id:integer,因此它可以像这样创建关联:

add_column :users, :account_id, :integer
add_index  :users, :account_id

在此先感谢您的帮助。我认为这是我忽略的小事。

你有

has_many :users

所以你必须使用

accepts_nested_attributes_for :users