Add a has_many
to the User
model like this:
has_many :admin_children, foreign_key: :created_by_user_id, class_name: "User"
Then you can do:
current_user.admin_children.create(user_create_params)
Question
In my user model, I have
belongs_to :admin_creator, foreign_key: :created_by_user_id, class_name: "User"
and in my create controller action I have...
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
How can I recast my code to to use model association for "current_user" who would be the admin_creator?
When create action is called, current_user is the current admin user who is adding another (child) user account. I'm thinking it would be along the lines of... @user = current_user.users.build(user_create_params) or similar
Solution
Add a has_many
to the User
model like this:
has_many :admin_children, foreign_key: :created_by_user_id, class_name: "User"
Then you can do:
current_user.admin_children.create(user_create_params)