How to create/update record if some variables are not set through strong params?

Some of the variables are required for a record but not included in the params. How to then create/update such a record? Would the code below be correct? I belief the new method works, but have doubts about the update method.

New record:

connect = Connect.new(update_params(connection))
connect.first_id = comp1.id
connect.second_id = comp2.id
connect.save

Update existing record:

#If record exists, do this:
connect.first_id = comp1.id
connect.second_id = comp2.id
if connect.save
  unless connect.update_attributes(update_connection_params(connection))
    return render json: @organization, message: connect.errors.full_messages, status: :bad_request
  end
end

Answers


Just write validations for these fields, on validation error(s) the record will not be saved and save will return false.

Common pattern is to render the form again, with errors, asking the user to correct

Your code for new record is correct, just check return value of save like for existing:

connect.assign_attributes update_connection_params(connection)
connect.first_id = comp1.id
connect.second_id = comp2.id
if connect.save
  redirect_to somewhere_path
else
  return render json: @organization, message: connect.errors.full_messages, status: :bad_request
end

Need Your Help

C fwrite and file size

c file fopen fwrite

I'm confused of a strange problem. When I make something like below:

How do i configure optional flags in MVC 1.0 routes

.net asp.net-mvc

I want to configure a route with optional flags.