Marty
Marty

Reputation: 2224

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

Upvotes: 1

Views: 27

Answers (1)

Vasfed
Vasfed

Reputation: 18464

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

Upvotes: 1

Related Questions