dnyanesh
dnyanesh

Reputation: 99

Rails update one to one and one to many - create child object if not exist

I have three models: Employee, User, and Role. Relationship between these classes are employee --- one_to_one -- user and user -- one_to_many -- role.

My create action is working fine with following strong params methods

def employee_params
  params.require(:employee).permit(:first_name, :middle_name, :last_name, :email, user_attributes: [:id, role_ids:[]])
end

For update if employee record has no user object, I am instantiating new user, mapping it to employee and calling update by passing string params. However, the update is failing with message:

Failed to save the new associated user

My update method code is

def update
  @employee = Employee.find(params[:id])
  if params[:employee][:user_attributes] != nil && params[:employee][:user_attributes][:role_ids] != nil && ! params[:employee][:user_attributes][:role_ids].empty?
    if @employee.user == nil
      @employee.user = User.new
      temp_password = Devise.friendly_token.first(8)
      @employee.user.is_temp_password = true
      @employee.user.password = Devise.friendly_token.first(8)
      @employee.user.email = @employee.email
      @employee.user.email = params[:employee][:email] if  params[:employee][:email]
    end
  end
  respond_to do |format|
    if @employee.update(employee_params)
      format.json { render json: @employee.as_json}
    else
      format.json {render :json => @employee.errors.as_json, :status => 422}
    end
  end
end

Upvotes: 0

Views: 250

Answers (1)

Maged Makled
Maged Makled

Reputation: 1986

I think as the above users suggested, you need to save the new User Object but also I think you should have the User creation code inside of the Employee create since you you would need to auto create it anyways in the update

Not sure if you also aware of helpers blank?, present? but I rewrote your code with that

def update
  @employee = Employee.find(params[:id])
  if params[:employee][:user_attributes].present? && params[:employee][:user_attributes][:role_ids].present? && params[:employee][:user_attributes][:role_ids].present?    
    unless @employee.user
      user = User.new
      @employee.user = user
      temp_password = Devise.friendly_token.first(8)
      user.is_temp_password = true
      user.password = Devise.friendly_token.first(8)
      user.email = @employee.email
      user.email = params[:employee][:email] if  params[:employee][:email]
      user.save!
    end
  end

Upvotes: 0

Related Questions