我的 API PeopleController 中有一个 Create 方法,用于创建人员、公司、电子邮件地址和电话号码。我有一种感觉,我需要将所有这些代码包装在一个事务中,以便在代码块末尾出现问题时一切都回滚(如果person.save在底部失败,我仍然以 Company、Emails 结尾等在数据库中)。
做这个的最好方式是什么?我也可以将所有条件逻辑放在事务块中吗?
def create
person = Person.new(person_params)
person.created_by = current_user.id
person.account = current_account
if params["company"] && params["company"].length > 1
person.company_id = Company.where(name: params["company"], account_id: current_account.id).first_or_create.id
end
if params["emails"]
if params["emails"]["primary"].length > 4
person.email_addresses << EmailAddress.create(address: params["emails"]["primary"], addressType: params["emails"]["primary_type"])
end
if params["emails"]["secondary"] && params["emails"]["secondary"].length > 4
person.email_addresses << EmailAddress.create(address: params["emails"]["secondary"], addressType: params["emails"]["secondary_type"])
end
end
if params["phonenumbers"]
if params["phonenumbers"]["primary"].length > 4
person.phone_numbers << PhoneNumber.create(number: params["phonenumbers"]["primary"], numberType: params["phonenumbers"]["primary_type"])
end
if params["phonenumbers"]["secondary"] && params["phonenumbers"]["secondary"].length > 4
person.phone_numbers << PhoneNumber.create(numberType: params["phonenumbers"]["secondary"], numberType: params["phonenumbers"]["secondary_type"])
end
end
person.save
render json: "Person saved."
end