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

问题描述 投票:1回答:1

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

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

目前我收到以下错误:

/ accounts / new中的ArgumentError找不到名称“user”的关联。它已经定义了吗?

我已经完成了我的模型和控制器,似乎无法解决这个问题。

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

我还在我的用户表上设置了account_id:integer,因此它可以在创建时进行关联:

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

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

ruby-on-rails nested-forms
1个回答
4
投票

你有

has_many :users

所以你必须使用

accepts_nested_attributes_for :users
© www.soinside.com 2019 - 2024. All rights reserved.