创建一个rails 5应用程序,使用devide和acts_作为tennant。
不太确定哪里出错了,我试图在accounts/new下以相同的形式创建帐户和帐户所有者。
目前我得到以下错误:
参数错误位于/accounts/new
找不到名称“user”的关联。定义好了吗?
我已经检查过我的模型和控制器,但似乎还没搞清楚。
会计学士学位
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
帐户控制器.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
用户地址
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
提前谢谢你的帮助。我想这是我忽略的一件小事。