Home > Net >  Rails: Find or initialize and then merge in params
Rails: Find or initialize and then merge in params

Time:10-05

I use find_or_initialize_by in my controller and then would like to apply the additional params to the record, whether new or existing. Is this possible to do in a Railsy way or do I have to loop through the parameters?

def create
  re_evaluation = @client.re_evaluations.find_or_initialize_by(program_id: re_evaluation_params[:program_id], check_in_id: re_evaluation_params[:check_in_id])

  # apply remaining re_evaluation_params here

  if re_evaluation.save
    render json: re_evaluation, status: :created
  else
    render json: re_evaluation.errors.full_messages, status: :unprocessable_entity
  end
end

CodePudding user response:

You should be able to assign the parameters as you'd do normally.

re_evaluation.assign_attributes(re_evaluation_params)

if re_evaluation.save
  ...
  • Related