1

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

user1322092
  • 4,020
  • 7
  • 35
  • 52

1 Answers1

1

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)
Rajesh Kolappakam
  • 2,095
  • 14
  • 12
  • Wow, that was quick!! Worked like a charm. – user1322092 Sep 27 '13 at 03:14
  • Not really related but same source as above - in this post, I asked a question regarding best practice when saving model data: http://stackoverflow.com/questions/19042063/rails-which-is-a-better-approach-to-saving-model-updates – user1322092 Sep 27 '13 at 03:17