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

时间:2019-03-03 00:09:46

标签: ruby-on-rails nested-forms

使用devise和act_as tennant构建Rails 5应用程序。

不太清楚我要去哪里,我正在尝试以相同的形式在accounts / new下创建帐户和帐户所有者。

目前,我遇到以下错误:

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

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

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,因此它可以像这样在create上建立关联:

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

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

1 个答案:

答案 0 :(得分:4)

你有

has_many :users

所以您必须使用

accepts_nested_attributes_for :users