在我的用户模型中,我有
belongs_to :admin_creator, foreign_key: :created_by_user_id, class_name: "User"
在我的创建控制器操作中我有......
def create
@user = User.new(user_create_params)
@user.created_by_user_id = current_user.id
@user.status_code = 'P' #set status code to pending
begin
@user.save!
render json: "User #{@user.email} added", status: :created
rescue StandardError => e
render json: @user.errors.full_messages, status: :unprocessable_entity
end
end
如何重新编写代码以使用“current_user”的模型关联作为admin_creator?
调用create action时,current_user是添加另一个(子)用户帐户的当前管理员用户。我认为这将是... @user = current_user.users.build(user_create_params)或类似的
答案 0 :(得分:1)
将has_many
添加到User
模型中,如下所示:
has_many :admin_children, foreign_key: :created_by_user_id, class_name: "User"
然后你可以这样做:
current_user.admin_children.create(user_create_params)