我想减少Rails项目中的重复代码。
def update_receipt
user = current_user
Receipt.update(user.receipt.id, name: params[:name].to_s, phone_number: params[:phone_number].to_s, address: params[:address].to_s, receipt_type: params[:receipt_type].to_i)
Receipt.update(user.receipt.id, name: params[:name].to_s, phone_number: params[:phone_number].to_s, address: params[:address].to_s, receipt_type: params[:receipt_type].to_i, tax_number: params[:tax_number].to_i) if params[:receipt_type].to_i == 2
end
有没有更好的方法来重构上述代码?
答案 0 :(得分:0)
更新回答:
def update_receipt
attrs = params.slice(:phone_number, :address, :receipt_type)
attrs[:tax_number] = params[:tax_number] if attrs[:receipt_type].to_i == 2
Receipt.update(user.receipt.id, attrs)
end